使用php将多维数组转换为单个数组

时间:2017-05-18 13:35:44

标签: php arrays multidimensional-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.2017
    )
   )

我想删除密钥0,1,2 我希望我的阵列像这样

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

我怎样才能使用php

3 个答案:

答案 0 :(得分:2)

检查array_reduce ()内置函数

<?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);

然后输出:

原始阵列:

  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
        )

)

输出:

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

获取更多帮助

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

答案 1 :(得分:0)

试试这个,

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

答案 2 :(得分:0)

您可以将RecursiveIteratorIteratoriterator_to_array功能一起使用:

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

这是working demo