json_encode多维数组的某些元素

时间:2015-10-09 13:03:35

标签: php json multidimensional-array

我有一个多维数组$ people,看起来像:

Array
    (
[0] => Array
       (
        [id] => 2
        [name] => John
        [address] => 
        [city] => 
        [postcode] => 
        [updated_at] => 2015-06-01 13:18:32
        [created_at] => 0000-00-00 00:00:00
    )

[1] => Array
    (
        [id] => 4
        [name] => Paul
        [address => 
        [city] => 
        [postcode] => 
        [updated_at] => 2015-06-26 10:59:58
        [created_at] => 2015-06-01 13:20:30
    )
 )

我想从这些数据中生成一些JSON,但它只包含每个数据的ID和名称。例如:

    [
         {
             "name-ref": "john",
             "identifier": "2"
         },
         {
             "name-ref": "Paul",
             "identifier": "4"
         }
    ]

请注意,它们的名称也不同。我怎么能这样呢?

三江源

2 个答案:

答案 0 :(得分:1)

这应该做的工作。尝试一下,如果不是你想要的那个,请告诉我答案。

    $outputArray = array();
foreach ($givenArray as $key => $value) {
    # code...
    $outputArray[$key]['name-ref'] = $value['name']
    $outputArray[$key]['identifier'] =  $value['id']
}

echo json_encode(array_values($outputArray));
}

答案 1 :(得分:0)

<?php

$final_array = array();
$count = 0;

foreach ($people as $p){
   $final_array[$count]['id'] = $p['id'];
   $final_array[$count]['name'] = $p['name'];
   $count++;
}

echo json_encode ($final_array);

?>