在PHP中将值分配给JSON

时间:2014-03-20 07:10:03

标签: php json

我创建了一个JSON

   $total_pages = 1;
    $device_details=array('devices'=> array(), 'total_pages');
     while ($rows_fetch = mysqli_fetch_assoc($mysql_all_resultset))
            {
                $details =array('name' => $rows_fetch['name'], 'latitude' => $rows_fetch['currentLatitude'], 'longitude' => $rows_fetch['currentLongitude']);
            array_push($device_details['devices'],$details);
            }
array_push($device_details['total_pages'], $total_pages);

此处添加了设备详细信息,但总页数不会添加到JSON并提供解析错误

3 个答案:

答案 0 :(得分:3)

你不能那样使用array_push。而是把它放在下面..

$device_details['total_pages'] = $total_pages;

无法使用array_push在特定密钥上插入值。


使用特定键上的简单插入array_push失败的插图。

<?php
$new=array();
array_push($new['car'],'hello');
print_r($new);

<强> OUTPUT :

Warning: array_push() expects parameter 1 to be array, null given in /tmp/execpad-cf3c45951562/source-cf3c45951562 on line 3
Array
(
    [car] => 
)

答案 1 :(得分:0)

 $total_pages = 1;
 // when you construct the array, do it.
 $device_details=array('devices'=> array(), 'total_pages' => $total_pages);
 while ($rows_fetch = mysqli_fetch_assoc($mysql_all_resultset)) {
    $device_details['devices'][] = array(
          'name' => $rows_fetch['name'], 
          'latitude' => $rows_fetch['currentLatitude'], 
          'longitude' => $rows_fetch['currentLongitude']
    );
 }

答案 2 :(得分:0)

这一行:

$device_details=array('devices'=> array(), 'total_pages');

应该是

$device_details=array('devices'=> array(), 'total_pages' => array());

如果你想使用数组推送