Multidimensional array to array

给你一囗甜甜゛ 提交于 2019-12-18 07:00:27

问题


I often have a 2-dimensional array:

array(
  array('key' => 'value1'),
  array('key' => 'value2'),
  ...
);

And need to form a 1-dimensional array:

array('value1', 'value2')

This can easily be done with foreach, but I wonder if there's some php 5.3 way to do it in one line.


回答1:


$new_array = array_map(function($el) { return $el['key']; }, $array);



回答2:


<?php
    $arr = array(array(141,151,161,140),2,3,array(101,202,array(303,404),407));
    function array_oned($arrays){
        static $temp_array = array();
        foreach($arrays as $key){
            if(is_array($key)){
                array_oned($key);
            }else {
                $temp_array [] = $key;
            }
        }
        return $temp_array;
    }
    echo print_r(array_oned($arr));

?>

Did you mean something like this ?




回答3:


array_reduce($array,function($arr,$new){
    $arr[]=$new['key'];
},array())



回答4:


In case, when you have only one value in inner arrays:

$values = array_map('array_pop', $yourArray);

Callback could be function name, so why reimplement something that already exists as a core function? :)



来源:https://stackoverflow.com/questions/6940217/multidimensional-array-to-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!