首頁  >  文章  >  後端開發  >  如何在 PHP 中有效合併關聯數組並處理缺失列?

如何在 PHP 中有效合併關聯數組並處理缺失列?

Linda Hamilton
Linda Hamilton原創
2024-10-20 21:42:02490瀏覽

How to Effectively Merge Associative Arrays and Handle Missing Columns in PHP?

合併關聯數組並用預設值補全缺失的欄位

考慮以下程式碼:

<code class="php">$a = ['a' => 'some value', 'b' => 'some value', 'c' => 'some value'];
$b = ['a' => 'another value', 'd' => 'another value', 'e' => 'another value', 'f' => 'another value'];
$c = ['b' => 'some more value', 'x' => 'some more value', 'y' => 'some more value', 'z' => 'some more value'];

$d = [$a, $b, $c];</code>

當您🎜>當您使用var_export($d),您將得到以下輸出:

<code class="php">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',
  ),
)</code>

將數組鍵與預設值合併

組合數組鍵並填充缺少的列使用默認值,您可以使用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);
}

echo '<pre class="brush:php;toolbar:false">';
print_r($data);</code>

結果:

<code class="php">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>

另一種方法

或者,您可以建立金鑰對值,然後合併它們:

<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 中有效合併關聯數組並處理缺失列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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