假设我有以下JSON字符串:
$json = '[{"Name":" Jim", "ID":"23", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]';
我如何只在更新的JSON字符串中显示属性'Name'?例如,我希望在更新的变量$json2
中将代码转换为此代码:
$json2 = '[{"Name":" Jim"},{"Name":" Bob"}]';
我尝试使用下面的代码执行此操作,但收到以下错误:
注意:未定义的索引:第9行的名称
$json = '[{"Name":" Jim", "ID":"23", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]';
$decode = json_decode($json, 'false');
$json2 = json_encode($decode['Name']);
echo $json2;
$json2
返回'null'。
答案 0 :(得分:2)
对于PHP 5.3 +:
<?php
$json = '[{"Name":" Jim", "ID":"23", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]';
$decode = json_decode($json, true);
$newArray = array_map(function ($array) {
return ['Name' => $array['Name']];
}, $decode);
echo json_encode($newArray);
答案 1 :(得分:2)
$json = '[{"Name":" Jim", "ID":"23", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]';
$decoded = json_decode($json, true);
$transformed = array_map(function (array $item) {
return array_intersect_key($item, array_flip(['Name']));
}, $decoded);
$json2 = json_encode($transformed);
array_intersect_key
是the easiest method从数组中提取特定键,并且在整个数组中array_map
中执行此操作是您正在寻找的。 p>