0

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

?>
1
  • You can't have an array key twice. Commented Dec 19, 2015 at 20:31

2 Answers 2

2

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

Comments

1

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

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.