2

I have create one JSON

like

   $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);

Here device details has been added but total pages will not be add to JSON and gives an Parse error

3 Answers 3

3

You can't use array_push like that. Instead put it like below..

$device_details['total_pages'] = $total_pages;

It is not possible to insert a value on a particular key using array_push.


Illustration of array_push failure using a simple insert on a particular key.

<?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] => 
)
Sign up to request clarification or add additional context in comments.

Comments

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']
    );
 }

Comments

0

This line:

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

Should be

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

if you want to use array push

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.