angularjsBeginner
angularjsBeginner

Reputation: 43

convert multidimensional array to single array using php

hi i have array like:-

Array
  (
[0] => Array
    (
        [payment_id] => 3160
    )

[1] => Array
    (
        [action] => update
    )

[2] => Array
    (
        [date] => 2017-05-17 09:59:40
    )

[3] => Array
    (
        [payment_date] => 23.05.2017
    )
   )

i want to remove the key 0,1, 2 i want my array to be like this

 Array
 (
[payment_id] => 3160
 [action] => update
   [date] => 2017-05-17 09:59:40
    [payment_date] => 23.05.2017
)

how can i get this using php

Upvotes: 1

Views: 5236

Answers (3)

sevavietl
sevavietl

Reputation: 3792

You can use RecursiveIteratorIterator along with iterator_to_array function:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); 
$result = iterator_to_array($iterator,true);

Here is working demo.

Upvotes: 0

Shafiqul Islam
Shafiqul Islam

Reputation: 5690

check array_reduce () built in function

<?php
$your_array = array(0 => array('payment_id' => 3160), 1 => array('action' => 'update'), 2 => array('date' => '2017-05-17 09:59:40'), 3 => array('payment_date' => '23.05.201'));
echo "<pre>";
print_r($your_array);
$convert_array = array_reduce($your_array, 'array_merge', array());
echo "<pre>";
print_r($convert_array);

then output is :

Original Array :

  Array
(
    [0] => Array
        (
            [payment_id] => 3160
        )

    [1] => Array
        (
            [action] => update
        )

    [2] => Array
        (
            [date] => 2017-05-17 09:59:40
        )

    [3] => Array
        (
            [payment_date] => 23.05.201
        )

)

Output :

 Array
(
    [payment_id] => 3160
    [action] => update
    [date] => 2017-05-17 09:59:40
    [payment_date] => 23.05.201
)

for more help

http://php.net/manual/en/function.array-reduce.php

Upvotes: 2

LF-DevJourney
LF-DevJourney

Reputation: 28564

try this,

$result = [];
foreach($array as $v)
{
  $result[key($v)] = current($v);
}

Upvotes: 0

Related Questions