简体   繁体   English

解码整个数组并对其一部分进行编码

[英]Decode full array and encode part of it

Let's say I have the following JSON string: 假设我有以下JSON字符串:

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

How would I only display the property 'Name' in an updated JSON string? 我如何只在更新的JSON字符串中显示属性“名称”? For example, I would want the code to be transformed into this in an updated variable $json2 : 例如,我希望将代码转换为更新后的变量$json2

$json2 = '[{"Name":" Jim"},{"Name":" Bob"}]';

I have attempted to do this using the code below but receive the following error: 我尝试使用下面的代码执行此操作,但收到以下错误:

Notice: Undefined index: Name on line 9 注意:未定义的索引:第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'. $json2返回'null'。

For PHP 5.3+: 对于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);

The array_intersect_key is the easiest method to pluck specific keys from an array, and doing it in an array_map over a whole array is what you're looking for. array_intersect_key是从数组中提取特定键的最简单方法 ,而您正在寻找的是在array_map对整个数组进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM