The Codesee
The Codesee

Reputation: 3783

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

Upvotes: 2

Views: 72

Answers (2)

For 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);

Upvotes: 2

deceze
deceze

Reputation: 522382

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

Upvotes: 2

Related Questions