0

Is there a specific function to move array which is in array to the parent array as key or value.

array(5) { [0]=> array(1) { [0]=> string(2) "id" } [1]=> array(1) { [0]=> string(7)
"buydate" } [2]=> array(1) { [0]=> string(6) "expire" } [3]=> array(1) { [0]=> string(6) 
"planid" } [4]=> array(1) { [0]=> string(5) "buyer" } } 

Result I would like to get is:

array() { [0] => 'id', [1] => 'buydate' etc. }

Or

array('id', 'buydate' etc.. )

Is it possible to achieve without foreach ?

3
  • any reason why you dont want foreach? Commented May 7, 2014 at 21:52
  • I prefer using functions instead of using foreach each time. Commented May 7, 2014 at 21:55
  • ... and what do you think that function is using... Commented May 7, 2014 at 23:04

2 Answers 2

1

array_map() is extremely powerful and should do the trick:

$array = ... ; // your initial array
$flattened_array = array_map(function($item) {
    return $item[0];
}, $array);
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to flatten the desired array, and use foreach you can do it this way.

Consider this example:

// Sample data:
$values = array(
    0 => array(
        0 => 'id',
    ),
    1 => array(
        0 => 'buydate',
    ),
    2 => array(
        0 => 'expire',
    ),
    3 => array(
        0 => 'planid',
    ),
    4 => array(
        0 => 'buyer',
    ),
);

$new_values = array();
foreach($values as $key => $value) {
    $new_values[] = $value[0];
}


print_r($new_values);

Sample Output:

Array
(
    [0] => id
    [1] => buydate
    [2] => expire
    [3] => planid
    [4] => buyer
)

Or alternatively, you can you the iterator. Consider this example:

$new_values = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($values));
foreach($iterator as $value) {
    $new_values[] = $value;
}

It should gave you the same output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.