Skip to content
Advertisement

How to encode json array inside foreach loop using Php

I am working with Php and Rest Api, i am trying encode data (fetching from database) using foreach loop,but data is not displaying as expected,”result” is showing three time instead of one,Here is my current code

$users = Services::all();
        $result = array();
        foreach ($users as $item) {
            $data = array('result' => array('image' => $item['image']));
            array_push($result, $data);
        }
        echo json_encode($result);

Here is my current output

[{"result":{"image":"abc.jpg"}},{"result":{"image":"abc2.jpg"}},{"result":{"image":"abc3.jpg"}}]

But i want “result” should display one time and other data (image) display multiple times (using loop)

Advertisement

Answer

Actually, for each item you are adding a result:item pair.

If I understand well, what you want is {result:{pair1,pair2,…,pairN}} with a pair beeing {image:data}

To do so, you have two options :

First you can create your pair list and add it to the final array with the key result.

To do so your code may look like this :

$users = Services::all();
$data_array = array();
foreach ($users as $item) {
    array_push($data_array, array('image' => $item['image']));
}
$result = array('result' => $data_array);
echo json_encode($result);

Second (and maybe best solution for ressource usage) you can add your data to a preinitialised array with the key “result”, like this :

$users = Services::all();
$result_array = array('result' => array());
foreach ($users as $item) {
    array_push($result_array['result'], array('image' => $item['image']));
}
echo json_encode($result_array);

Haven’t tested my code but the main idea is here.

ADD: The first one is just a redundant version of the second one, but it is useful to have the two code side by side to understand the difference, or to use them for different purpose.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement