Tuesday, 28 August 2018

PHP - JSON array can not return the value associated with the indexless name

I have a json array that looks like this:

[{"name":"title_one","value":"something"},{"name":"title_two","value":"something 2"},{"name":"title_three","value":"something three"}]

I can get the array and access values like so:
$configarray = json_decode($configfile, true);

$valueone = $configarray[0]['value'];
$valuetwo = $configarray[1]['value'];
$valuethree = $configarray[2]['value'];

BUT I will have different pairs (and thus different orders) at different times in this json, so I would like to access these values by getting their associated name, I have tried variations on:
 $valueone = $configarray['title_one']['value'];
 $valuetwo = $configarray['title_two']['value'];
 $valuethree = $configarray['title_three']['value'];

but it fails and tells me I have an undefined index. How can I access these values by the name in the pair?

Assuming you only have two properties inside of each json object you can do something like this:
$configfile  = '[{"name":"title_one","value":"something"},{"name":"title_two","value":"something 2"},{"name":"title_three","value":"something three"}]';
$configarray = json_decode($configfile, true);
$configarray = array_combine(array_column($configarray, 'name'), array_column($configarray, 'value'));

$valueone   = $configarray['title_one'];
$valuetwo   = $configarray['title_two'];
$valuethree = $configarray['title_three'];

0 comments:

Post a Comment