2017-04-24 48 views
0

我有一個關聯數組(實際上是一個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) "[email protected]" 
     ["uri"] => string(0) "" 
    } 
} 

我怎麼能結合整個事情與自己,所以我結束了以下?

預期輸出:

array(3) { 
    [0] => array(4) { 
     ["firstname"] => string(21) "John" 
     ["lastname"] => string(0) "Smith" 
     ["email"] => string(0) "[email protected]" 
     ["uri"] => string(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" => "[email protected]", 
     "uri" => "") 
); 
$result=array(); 
foreach($array as $value) 
{ 
    $result= array_merge($result,array_filter($value)); 
} 
$result["uri"]=""; 
print_r(array($result)); 
1

薩赫勒的回答並不是很穩定/可信的,因爲它手動校正失蹤uri鍵的值的過程完成之後。這種調整純粹是因爲缺少的值對程序員是「已知的」。從程序上講,這是懶惰的,容易失敗,不應該被SO讀者使用。

下面是一個方法,執行速度可能會更快(因爲它使用較少的函數可能會更快,但我沒有打算進行基準測試),完成後沒有任何東西需要掃描。所有的子數組元素都被組合成$array[0]作爲結果數組。

輸入:

$array= [ 
      ["firstname"=>"John","lastname"=>"","email"=>"","uri"=>""], 
      ["firstname"=>"","lastname"=>"Smith","email"=>"","uri"=>""], 
      ["firstname"=>"","lastname"=>"","email"=>"[email protected]","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' => '[email protected]', 
    '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); 

*注意,以防萬一你的實際項目中有比你發佈四個字段以及那些字段中的一個更可以認爲你不希望過濾掉零值,使用strlen作爲參數在array_filter()