0

无法从 PHP json_encode 转换或访问 JSON 对象

<?php
$f_array = array();   // ---- Custom Line 1
for ($i=0; $i < $interval; ++$i) 
{
    $t_date = date('Y-m-d', strtotime($k_date1 . "+ $i day"));    

    $f_array = array();
    $f_query = mysql_query("select COUNT(j.job_id) as `job_count`
                            from jobs j
                            where j.job_posted_date 
                            LIKE '%$t_date%' and j.job_status = 3");

    if (mysql_num_rows($f_query) > 0) 
    {
        $f_query_data = mysql_fetch_array($f_query);
        $f_count = $f_query_data['job_count'];

        $f_array = array_push($f_array, $f_count);   // ---- Custom Line 2
        // $f_array[] = $f_count;   // ---- Custom Line 3
    }
}

$j_array = json_encode($f_array);
?>

我只得到一个值,即1在 Javascript 中,使用enabling Custom Line 1& Custom Line 2

当 ienabled Custom Line 3和禁用Custom Line 1& Custom Line 2。然后我得到像从数据库一样好的输出

<script>
var j_array = "<?php echo $j_array; ?>";
</script>

结果 1

<script>
var j_array = "1";
</script>

结果 2

<script>
var j_array = "["0","0","0","2","0","0","0","0","1","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","2","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","25","0","0","0","0","0","7","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","1","0","0","1","1","47","0","1","1","0","0","0","0","0","0","3","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"]";
</script>

我在下面附上了一张图片..

在此处输入图像描述

现在我如何Result 2按顺序Array或任何其他方法访问。

我尝试在下面使用

<script>
    alert(j_array);
</script>

<script>
    alert(j_array.0); // as an Object mightbe .. or I dont have any idea on it, so experimenting ..
</script>

我需要什么或需要帮助

它没有给出任何结果,因为0integer不是string..如果它是一个Array那么它也很棘手..有n很多String 0..所以我怎么能一个一个地打电话。或转换成 Javascript 数组。

注意:Result 2是所需的输出,但它不在Array

4

4 回答 4

2

看看 php 手册array_push()

返回数组中元素的新数量。

所以正确的语法是:

array_push($f_array, $f_count);   // without `$f_array = ` at the beginning
于 2012-10-29T14:38:28.820 回答
2

任何一个:

array_push($f_array, $f_count);

或者

$f_array[] = $f_count;

绝对不是 $f_array = array_push($f_array, $f_count)

接下来,JSON 数组周围没有引号,因为它变成了 Javascript 字符串:

var j_array = <?php echo $j_array; ?>;

接下来,访问 Javascript 数组元素,如下所示:

j_array[0]

不是 j_array.0

于 2012-10-29T14:40:36.783 回答
1

查看 的函数签名array_push()

它不返回扩展数组,而是使用第一个参数作为变量引用并返回一个整数。在Custom Line 2上,您将返回值分配array_push()给您的数组,这就是为什么您总是得到1结果。

删除自定义行 2 上的分配,如下所示,您将得到您所期望的:

array_push($f_array, $f_count);
于 2012-10-29T14:37:47.543 回答
1
var j_array = <?php echo $j_array; ?>;

没有 ” ”

当您放置括号时,您会在 javascript 中转义 json_encoded 数组。

于 2012-10-29T14:38:07.120 回答