-1

how can i make this Array:

array(2) {
  [0]=>
  array(1) {
    ["plz"]=>
    string(4) "4460"
  }
  [1]=>
  array(1) {
    ["plz"]=>
    string(4) "4000"
  }
}

Becomes something like this just need the values in one array keys doesnt matter:

array(2) {
  [0]=>
  string(4) "4460"
  [1]=>
  string(4) "4000"
}

is there a helper function or something which can help?

user2834172
  • 861
  • 1
  • 9
  • 17

2 Answers2

7

If key is known beforehand:

If you're using PHP 5.5+, you can use array_column() to extract all the sub-arrays with plz key:

$result = array_column($array, 'plz');

The same can be achieved using array_map() if you're using an older version of PHP:

$result = array_map(function($sub) { return $sub['plz']; }, $array);

If key is not known beforehand:

Use array_walk_recursive():

$result = array();
array_walk_recursive($array, function($v) use (&$result) { $result[] = $v; });

Note that it works recursively, so it'd still work if you have more complex arrays.

Alternatively, you could use RecursiveIteratorIterator class:

$result = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));

foreach($iterator as $value) {
    $result[] = $value;
}

For more details, see this question: How does RecursiveIteratorIterator work in PHP?

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
2

Another alternative:

$array = call_user_func_array('array_merge', array_map('array_values', $array));
  1. Get numerically indexed arrays from the sub-arrays using using array_values()
  2. Merge those arrays using array_merge()
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87