将关联数组的子项合并为一个

时间:2017-04-24 14:51:31

标签: php arrays merge

我有一个具有这种结构的关联数组(实际上是一个Laravel集合):

array(3) {
    [0] => array(4) {
        ["firstname"] => string(21) "John"
        ["lastname"] => string(0) ""
        ["email"] => string(0) ""
        ["uri"] => string(0) ""
    }
    [1] => array(4) {
        ["firstname"] => string(0) ""
        ["lastname"] => string(22) "Smith"
        ["email"] => string(0) ""
        ["uri"] => string(0) ""
    }
    [2] => array(4) {
        ["firstname"] => string(0) ""
        ["lastname"] => string(0) ""
        ["email"] => string(19) "john@example.org"
        ["uri"] => string(0) ""
    }
}

我如何将整个事物与自身结合起来,所以我最终会得到以下内容?

预期输出:

array(3) {
    [0] => array(4) {
        ["firstname"] => string(21) "John"
        ["lastname"] => string(0) "Smith"
        ["email"] => string(0) "john@example.org"
        ["uri"] => string(0) ""
    }
}

我确信这是一个不费脑子的事情,但现在我想念森林的树木......提前谢谢。

2 个答案:

答案 0 :(得分:1)

我们正在使用array_mergearray_filterarray_merge会将数组合并到另一个数组中,array_filter将过滤数组以获取空值。

Try this code snippet here

<?php

$array = array(
    0 => array(
        "firstname" => "John",
        "lastname" => "",
        "email" => "",
        "uri" => ""
    ),
    1 => array(
        "firstname" => "",
        "lastname" => "Smith",
        "email" => "",
        "uri" => ""
    ),
    2 => array(
        "firstname" => "",
        "lastname" => "",
        "email" => "john@example.org",
        "uri" => "")
);
$result=array();
foreach($array as $value)
{
    $result=  array_merge($result,array_filter($value));
}
$result["uri"]="";
print_r(array($result));

答案 1 :(得分:1)

Sahil的答案不是非常强大/值得信赖,因为它会在流程完成后手动更正丢失的uri密钥的值。这种调整完全是因为缺少的值对于程序员来说是“已知的”。从编程上讲,这是懒惰的,容易失败,不应该被SO读者使用。

这是一种执行速度同样快的方法(可能更快,因为它使用较少的功能,但我没有费心去测试它),完成时没有任何东西可以用来扫描。所有子数组元素都组合成$array[0]作为结果数组。

输入:

$array= [
            ["firstname"=>"John","lastname"=>"","email"=>"","uri"=>""],
            ["firstname"=>"","lastname"=>"Smith","email"=>"","uri"=>""],
            ["firstname"=>"","lastname"=>"","email"=>"john@example.org","uri"=>""]
        ];

方法:

$result=array_splice($array,0,1);  // preserve all "columns"
foreach($array as $subarray){
    foreach($subarray as $k=>$v){
        if($v!=''){$result[0][$k]=$v;}  // only overwrite where a non-empty value exists
    }
}
var_export($result);

输出:

array (
  'firstname' => 'John',
  'lastname' => 'Smith',
  'email' => 'john@example.org',
  'uri' => '',
)

这是使用array_merge()array_filter()的正确/可靠方法:

$result=array_splice($array,0,1);
foreach($array as $subarray){
    $result[0]=array_merge($result[0],array_filter($subarray,'strlen'));
}
var_export($result);

*请注意,如果您的实际项目超过发布的四个字段且其中一个字段可能保持您不想过滤掉的零值,请使用{{1 }}作为strlen中的参数。