Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert multidimensional array into single array

Tags:

arrays

php

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?

like image 279
CuriousMind Avatar asked Jul 22 '11 03:07

CuriousMind


People also ask

How do I make multiple arrays into one array?

Using concat method The concat method will merge two or more arrays into a single array and return a new array. In the code above, we have merged three arrays into an empty array. This will result in merging multiple arrays into a new array.

How do you make a single array?

const arr = [ [ {"c": 1},{"d": 2} ], [ {"c": 2},{"d": 3} ] ]; We are required to write a JavaScript function that takes in one such array as the first and the only argument. The function should then convert the array (creating a new array) into array of objects removing nested arrays.


2 Answers

This single line would do that:

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

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

For details, go to official documentation: https://www.php.net/manual/en/function.array-column.php.

like image 195
Usman Ahmed Avatar answered Oct 11 '22 10:10

Usman Ahmed


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;  }  
like image 29
AlienWebguy Avatar answered Oct 11 '22 09:10

AlienWebguy