首頁  >  文章  >  後端開發  >  如何合併關聯數組與缺失列的預設值?

如何合併關聯數組與缺失列的預設值?

Susan Sarandon
Susan Sarandon原創
2024-10-20 21:38:30987瀏覽

How to Merge Associative Arrays with Default Values for Missing Columns?

將關聯數組與缺失列的預設值合併

要合併多個關聯數組並使用預設值填充缺失列,您可以利用PHP 數組函數的強大功能。

問題

考慮以下陣列:

$a = array('a' => 'some value', 'b' => 'some value', 'c' => 'some value');
$b = array('a' => 'another value', 'd' => 'another value', 'e' => 'another value', 'f' => 'another value');
$c = array('b' => 'some more value', 'x' => 'some more value', 'y' => 'some more value', 'z' => 'some more value');

當您使用var_export 合併這些陣列時,您得到:

array (
  0 => 
  array (
    'a' => 'some value',
    'b' => 'some value',
    'c' => 'some value',
  ),
  1 => 
  array (
    'a' => 'another value',
    'd' => 'another value',
    'e' => 'another value',
    'f' => 'another value',
  ),
  2 => 
  array (
    'b' => 'some more value',
    'x' => 'some more value',
    'y' => 'some more value',
    'z' => 'some more value',
  ),
)

解決方案

要組合數組鍵並用空字串填充缺失的列,您可以使用array_merge:
<code class="php">$keys = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($d)) as $key => $val) $keys[$key] = '';
$data = array();
foreach($d as $values) {
    $data[] = array_merge($keys, $values);
}</code>

這將產生所需的輸出:
Array
(
    [0] => Array
        (
            [a] => some value
            [b] => some value
            [c] => some value
            [d] => 
            [e] => 
            [f] => 
            [x] => 
            [y] => 
            [z] => 
        )

    [1] => Array
        (
            [a] => another value
            [b] => 
            [c] => 
            [d] => another value
            [e] => another value
            [f] => another value
            [x] => 
            [y] => 
            [z] => 
        )

    [2] => Array
        (
            [a] => 
            [b] => some more value
            [c] => 
            [d] => 
            [e] => 
            [f] => 
            [x] => some more value
            [y] => some more value
            [z] => some more value
        )
)

另一個選項是建立具有空值的鍵對值並將它們合併:
<code class="php">$keys = array_keys(call_user_func_array('array_merge', $d));
$key_pair = array_combine($keys, array_fill(0, count($keys), null));
$values = array_map(function($e) use ($key_pair) {
    return array_merge($key_pair, $e);
}, $d);</code>

這也會產生相同的期望輸出。

以上是如何合併關聯數組與缺失列的預設值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn