多维数组转换为简单数组PHP

时间:2019-11-07 18:16:40

标签: php arrays

像这样的数组:

Array
(
    [0] => Array
        (
            [0] => <img s
            [1] => Ric
            [2] => 130
            [3] => 608
        )

    [1] => Array
        (
            [0] => In Stock
            [1] => 10 lb
            [2] => <img src=
            [3] => Rice La
        )
)

我想要的是将这个复杂的数组转换为一个简单的数组,所以最后,我可以得到以下结果:

Array
(

            [0] => <img s
            [1] => Ric
            [2] => 130
            [3] => 608
            [4] => In Stock
            [5] => 10 lb
            [6] => <img src=
            [7] => Rice La

)

我真的尝试了很多不同的代码,并在互联网上找到了这样的帮助:

    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; 
} 

这根本没有帮助我。有人知道我可以尝试解决此问题的方法吗?这根本没有帮助我。有人知道我可以尝试解决此问题的方法吗?

4 个答案:

答案 0 :(得分:2)

最简单的方法是通过splat ...运算符使用Argument unpacking合并它们:

$result = array_merge(...$array);

答案 1 :(得分:0)

$elements = array();
foreach ( $array as $mElement ) {
    foreach ( $mElement as $singleElement ) {
        $elements[] = $singleElement;
    }
}

print_r($elements);

假设$array包含:

Array
(
    [0] => Array
        (
            [0] => <img s
            [1] => Ric
            [2] => 130
            [3] => 608
        )

    [1] => Array
        (
            [0] => In Stock
            [1] => 10 lb
            [2] => <img src=
            [3] => Rice La
        )
)

您的输出将是:

Array
(

            [0] => <img s
            [1] => Ric
            [2] => 130
            [3] => 608
            [4] => In Stock
            [5] => 10 lb
            [6] => <img src=
            [7] => Rice La

)

答案 2 :(得分:0)

这会做到的。

$simplearray = array();
foreach($higharray as $midarray){
    foreach($midarray as $childarray){
        $simplearray[] = $childarray;
    }
}
print_r($simplearray)

答案 3 :(得分:0)

此功能可以满足您的需要,并且避免使用多个循环。

function array_flatten($array) {
    $temp = [];
    foreach($array as $a) {
        $temp = array_merge($temp, $a);
    }
    return $temp;
}