Ben February 2016

Convert array of objects with keys to keyed array

I have an array of objects that are defined as {'preference name',value}. For example

$preferences[] = {'abc',123};
$preferences[] = {'def',456};

I'd like to access them like this:

$pref = $preferences['abc'];

Of course, I know I could assign them as a keyed array to begin with, however I'm getting the values via JSON, and json_decode always creates an array of objects. Some example JSON that leads us to the situation above would be:

{'abc':123,'def':456}

Obviously it's trivial to covert these using a loop, but I wondered if there was a better one-liner that might do the job?

Answers


Gwendal February 2016

Seems ugly, but hey, it works.

<?php

$a = ['abc'=>123,'def'=>456];
$obj = json_decode(json_encode($a));
var_dump($obj->abc); //123
$arr = (array)$obj;
var_dump($arr["abc"]); //123


AbraCadaver February 2016

If you decode the JSON into associative arrays AND all properties are unique, then just merge the sub arrays:

$preferences = json_decode($json, true);
$preferences = call_user_func_array('array_merge', $preferences);

Post Status

Asked in February 2016
Viewed 2,796 times
Voted 12
Answered 2 times

Search




Leave an answer