获取多维数组上特定键的值

时间:2014-07-18 04:01:19

标签: php arrays multidimensional-array

Array([130] => Array
       (
        [0] => Array
            (
                [first_name] => John
                [last_name] => Smith
            )
        [1] => Array
            (
                [first_name] => Jane
                [last_name] => Doe
            )
    [123] => Array
      (
        [0] => Array
            (
                [first_name] => Ann
                [last_name] => Green
            )
        [1] => Array
            (
                [first_name] => Thor
                [last_name] => Grey
            )
        )

如何制作像这样的数组

   Array(
         [130] => Array
          (
            [first_name] => "John, Jane"
         [123] => Array
         (
           [first_name] => "Ann, Thor"
         )

1 个答案:

答案 0 :(得分:0)

以下是使用foreach()variable by reference的快速简单解决方案:

foreach($your_array as &$current) {
    $current = array(
        'first_name' => $current[0]['first_name'] . ', ' . $current[1]['first_name']
    );
}

但假设您的子阵列中可能有多个人而不是两个人,这是一个更好的解决方案:

foreach($your_array as &$current) {
    $to_append = array(); // use a temporary array
    foreach($current as $sub_array) {
        $to_append[] = $sub_array['first_name']; // add each first name to temp
    }
    // overwrite current main array iteration with imploded temporary array
    $current = array('first_name' => implode(', ', $to_append));
}

-

更新

以下是另一种不使用foreach()的解决方案,而是通过引用将array_walk()array_map()与变量结合使用:

array_walk($your_array, function(&$array_branch) {
    $names = array_map(function($a){
        return $a['first_name']; // return all the first names
    }, $array_branch);

    // combine the first names together
    $array_branch = array('first_name' => implode(', ', $names)); 
});

$array_branch表示主阵列中的每个数组(键130和123)并通过引用传递,因此每次都会覆盖其值