Convert multidimensional array into single array

2018-12-31 20:52发布

问题:

I have an array which is multidimensional for no reason

/* This is how my array is currently */
Array
(
[0] => Array
    (
        [0] => Array
            (
                [plan] => basic
            )

        [1] => Array
            (
                [plan] => small
            )

        [2] => Array
            (
                [plan] => novice
            )

        [3] => Array
            (
                [plan] => professional
            )

        [4] => Array
            (
                [plan] => master
            )

        [5] => Array
            (
                [plan] => promo
            )

        [6] => Array
            (
                [plan] => newplan
            )

    )

 )

I want to convert this array into this form

/*Now, I want to simply it down to this*/
Array (
[0] => basic
[1] => small
[2] => novice
[3] => professional
[4] => master
[5] => promo
[6] => newplan
)

Any idea how to do this?

回答1:

Assuming this array may or may not be redundantly nested and you\'re unsure of how deep it goes, this should flatten it for you:

function array_flatten($array) { 
  if (!is_array($array)) { 
    return FALSE; 
  } 
  $result = array(); 
  foreach ($array as $key => $value) { 
    if (is_array($value)) { 
      $result = array_merge($result, array_flatten($value)); 
    } 
    else { 
      $result[$key] = $value; 
    } 
  } 
  return $result; 
} 


回答2:

$array = array_column($array, \'plan\');

The first argument is an array | The second argument is array key.

Note: array_column was introduced in PHP 5.5 so it won\'t work in earlier versions.



回答3:

Just assign it to it\'s own first element:

$array = $array[0];


回答4:

 $singleArray = array();

    foreach ($multiDimensionalArray as $key => $value){
        $singleArray[$key] = $value[\'plan\'];
    }

this is best way to create a array from multiDimensionalArray array.

thanks



回答5:

For this particular case, this\'ll do:

$array = array_map(\'current\', $array[0]);

It\'s basically the exact same question is this one, look at some answers there: PHP array merge from unknown number of parameters.



回答6:

You can do it just using a loop.

    $singleArray = array();

    foreach ($multiDimensionalArray as $key => $value){
        $singleArray[$key] = $value[\'plan\'];
    }


回答7:

Recently I\'ve been using AlienWebguy\'s array_flatten function but it gave me a problem that was very hard to find the cause of.
array_merge causes problems, and this isn\'t the first time that I\'ve made problems with it either.
If you have the same array keys in one inner array that you do in another, then the later values will overwrite the previous ones in the merged array.

Here\'s a different version of array_flatten without using array_merge:

function array_flatten($array) { 
  if (!is_array($array)) { 
    return FALSE; 
  } 
  $result = array(); 
  foreach ($array as $key => $value) { 
    if (is_array($value)) { 
      $arrayList=array_flatten($value);
      foreach ($arrayList as $listItem) {
        $result[] = $listItem; 
      }
    } 
   else { 
    $result[$key] = $value; 
   } 
  } 
  return $result; 
} 


回答8:

I have done this with OOP style

$res=[1=>[2,3,7,8,19],3=>[4,12],2=>[5,9],5=>6,7=>[10,13],10=>[11,18],8=>[14,20],12=>15,6=>[16,17]];
class MultiToSingle{
public $result=[];
public function __construct($array){
    if(!is_array($array)){
        echo \"Give a array\";
    }
    foreach($array as $key => $value){
        if(is_array($value)){
            for($i=0;$i<count($value);$i++){
                $this->result[]=$value[$i];
            }  
        }else{
            $this->result[]=$value;
        }
    }
}
}

$obj= new MultiToSingle($res);
$array=$obj->result;
print_r($array);


回答9:

Multi dimensional array to single array with one line code !!! Enjoy the code.

$array=[1=>[2,5=>[4,2],[7,8=>[3,6]],5],4];
$arr=[];
array_walk_recursive($array, function($k){global $arr; $arr[]=$k;});
print_r($arr);

...Enjoy the code.



回答10:

Following this pattern

$input = array(10, 20, array(30, 40), array(\'key1\' => \'50\', \'key2\'=>array(60), 70));

Call the function :

echo \"<pre>\";print_r(flatten_array($input, $output=null));

Function Declaration :

function flatten_array($input, $output=null) {
if($input == null) return null;
if($output == null) $output = array();
foreach($input as $value) {
    if(is_array($value)) {
        $output = flatten_array($value, $output);
    } else {
        array_push($output, $value);
    }
}
return $output;

}



回答11:

Your sample array has 3 levels. Because the first level has only [0], you can hardcode your access into it and avoid an extra function/construct call.

(Code Demos)

  1. array_walk_recursive() is handy and versatile, but for this task may be overkill and certainly a bit more convoluted in terms of readability.

    array_walk_recursive($array, function($leafvalue)use(&$flat){$flat[] = $leafvalue;});
    var_export($flat);
    
  2. If this was my code, I\'d be using array_column() because it is direct and speaks literally about the action being performed.

    var_export(array_column($array[0], \'plan\'));
    
  3. Of course a couple of `foreach() loops will perform very efficiently because language constructs generally perform more efficiently than function calls.

    foreach ($array[0] as $plans) {
        foreach ($plans as $value) {
            $flat[] = $value;
        }
    }
    var_export($flat);
    
  4. Finally, as a funky alternative (which I can\'t imagine actually putting to use unless I was writing code for someone whom I didn\'t care for) I\'ll offer an array_merge_recursive() call with a splat operator (...).

    var_export(array_merge_recursive(...$array[0])[\'plan\']);
    


回答12:

$flattenArray = [];

foreach ($parentArray as $childArray) {
    foreach ($childArray as $value) {
        $flattenArray[] = $value;
    }
}


回答13:

Save this as a php file, simply import and use single_array() function

<?php
$GLOBALS[\'single_array\']=[];
function array_conveter($array_list){
    if(is_array($array_list)){
        foreach($array_list as $array_ele){
            if(is_array($array_ele)){
                array_conveter($array_ele);
            }else{
                array_push($GLOBALS[\'single_array\'],$array_ele);
            }
        }
    }else{
        array_push($GLOBALS[\'single_array\'],$array_list);
    }
}
function single_array($mix){
    foreach($mix as $single){
        array_conveter($single);
    }return $GLOBALS[\'single_array\'];
    $GLOBALS[\'single_array\']=[];
}
/* Example convert your multi array to single  */
$mix_array=[3,4,5,[4,6,6,7],\'abc\'];
print_r(single_array($mix_array));

?>


标签: php arrays