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

Linda Hamilton
發布: 2024-10-20 21:42:02
原創
489 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!