The Codesee The Codesee - 4 months ago 18
JSON Question

Decode full array and encode part of it

Let's say I have the following JSON string:

$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? For example, I would want the code to be transformed into this in an updated variable
$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


$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'.

Answer
$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.

Comments