Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

php - Multidimensional indexed array to associative array depending on column value

I have a multidimensional indexed array. Each element is an associative array with an id column which is unique between elements (its value never repeats within the array).

[indexed] =>Array
(
    [0] => Array
        (
            [id] => john
            [name] => John
            [age] => 29
        ),

    [1] => Array
        (
            [id] => peter
            [name] => Peter
            [age] => 30
        ),

    [2] => Array
        (
            [id] => harry
            [name] => Harry
            [age] => 19
        )
)

My goal is to convert this array into a multidimensional associative array, indexed by id values.

[indexed] =>Array
(
    [john] => Array
        (
            [id] => john
            [name] => John
            [age] => 29
        ),

    [peter] => Array
        (
            [id] => peter
            [name] => Peter
            [age] => 30
        ),

    [harry] => Array
        (
            [id] => harry
            [name] => Harry
            [age] => 19
        )
)

My best attempt so far is to loop over array elements and manually create the final array.

$associative = array();
foreach($indexed as $key=>$val) $associative[$val['id']] = $val;

I think it's not the most elegant solution. Is it possible to obtain the same result with built-in (more efficient) functions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The truth is php DOES offer a single, native function that allows you to replace the outer indexes with the values of a single column. The "magic" is in the 2nd parameter which tells php not to touch the subarray values when assigning the new keys.

Code: (Demo)

$indexed = [
    ['id' => 'john', 'name' => 'John', 'age' => 29],
    ['id' => 'peter', 'name' => 'Peter', 'age' => 30],
    ['id' => 'harry', 'name' => 'Harry', 'age' => 19],
];

var_export(array_column($indexed, null, 'id'));

Output:

array (
  'john' => 
  array (
    'id' => 'john',
    'name' => 'John',
    'age' => 29,
  ),
  'peter' => 
  array (
    'id' => 'peter',
    'name' => 'Peter',
    'age' => 30,
  ),
  'harry' => 
  array (
    'id' => 'harry',
    'name' => 'Harry',
    'age' => 19,
  ),
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...