我需要创建一个包含项目数组的JSON对象,并为每个项目创建他的品牌信息数组。
我需要得到这个结果:
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
)相反,我得到了这样的结果:
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 ) 
) 前端是一个带有对服务器的post请求的AJAX。前端的对象称为phone_items。
因此,当我输入firebug控制台phone.items.item_info时,我将获得该项目的CPU和内存: iphone。
这是我的php脚本
<?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);
?>发布于 2015-12-19 20:38:28
您需要分配项目信息,而不是仅仅将其推送到数组中。
做这样的事:
foreach ($all_items as $idx => $single_item){
    $all_items[$idx] = [
        'name' => $single_item, 
        'item_info' => getItemsInfo($single_item),
    ];
}然后,要回显有效的JSON:
echo json_encode($all_items);发布于 2015-12-19 20:38:43
您想要的确切输出是不可能的,因为数组元素有两个值("iphone“和"item_info”数组)。然而,只要稍微清理一下,我们就可以做一些非常接近的事情:
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);https://stackoverflow.com/questions/34375084
复制相似问题