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


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"
         )

这里有一个快速而简单的解决方案,使用foreach()和引用变量:

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),并通过引用传递,因此每次都覆盖它的值

相关内容

  • 没有找到相关文章

最新更新