解码完整数组并对其中的一部分进行编码

Decode full array and encode part of it

假设我有以下 JSON 字符串:

$json = '[{"Name":" Jim", "ID":"23", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]';

如何在更新后的 JSON 字符串中只显示 属性 'Name'?例如,我希望在更新的变量 $json2:

中将代码转换为 this
$json2 = '[{"Name":" Jim"},{"Name":" Bob"}]';

我尝试使用下面的代码执行此操作,但收到以下错误:

Notice: Undefined index: Name on line 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 returns 'null'.

对于 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);
$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 从数组中提取特定键,并在 array_map 中对整个数组执行此操作就是您要查找的内容。