Gilad Adar
Gilad Adar

Reputation: 193

Create array for each item to json object

I need to create a JSON object with array of items and for each item create array of his brand info.

I need to get this result:

Array
    (
      [0] => iphone
             [item_info]
                    [cpu] => cpu_cores
                    [memory] => memory_ram

      [1] => lg
             [item_info]
                    [cpu] => cpu_cores
                    [memory] => memory_ram


      [2] => nokia
             [item_info]
                    [cpu] => cpu_cores
                    [memory] => memory_ram
)

Instead, i am getting this result:

Array
( 
    [0] => iphone 
    [1] => android 
    [2] => nokia 
    [3] => Array ( [cpu] => cpu_cores [memory] => memory_ram ) 
    [4] => Array ( [cpu] => cpu_cores [memory] => memory_ram ) 
    [5] => Array ( [cpu] => cpu_cores [memory] => memory_ram ) 
) 

The front end is an AJAX with post request to the server. the object in the front end is called phone_items.

so when i will type in the firebug console phone.items[0].item_info i will get the CPU and the memory for the item: iphone.

Here is my php script

<?php

header('Content-type: application/json');

function getAllItems(){

    $items_array = ['iphone', 'android', 'nokia'];

    return $items_array;
}

function getItemsInfo($item){

    $item_info_array = [

        "cpu" => "cpu_cores",
        "memory" => "memory_ram",
    ];

    return $item_info_array;
}

$all_items = getAllItems();

foreach ($all_items as $single_item){

    $item_info = getItemsInfo($single_item);

    array_push($all_items, $item_info);
}

print_r($all_items);

?>

Upvotes: 0

Views: 43

Answers (2)

TwoStraws
TwoStraws

Reputation: 13127

The exact output you want isn't possible because your array elements have two values ("iphone" and also the "item_info" array). However, with a bit of a cleaning we can make something very close:

header('Content-type: application/json');

function getItemNames() {
    return ['iphone', 'android', 'nokia'];
}

function getItemsInfo($item) {
    return ["cpu" => "cpu_cores", "memory" => "memory_ram"];
}

$allItems = [];
$itemNames = getItemNames();

foreach ($itemNames as $itemName) {
    $info = getItemsInfo($itemName);
    $allItems[] = ['name' => $itemName, 'item_info' => $info];
}

print_r($allItems);

Upvotes: 1

segFault
segFault

Reputation: 4054

You need to assign the item info instead of just pushing it onto the array.

Do something like this:

foreach ($all_items as $idx => $single_item){
    $all_items[$idx] = [
        'name' => $single_item, 
        'item_info' => getItemsInfo($single_item),
    ];
}

Then to echo valid JSON:

echo json_encode($all_items);

Upvotes: 2

Related Questions