【问题标题】:Array splice with key name带有键名的数组拼接
【发布时间】:2021-04-17 02:36:33
【问题描述】:

我有 2 个数组($data_1 和 $data_2),它们有不同的值但有关系,我想合并这些数组,完全用键名

$data_1 = 
'[
    {
        "fruit": "apple",
        "weight": "15"
    },
    {
        "fruit": "durian",
        "weight": "50"
    },
    {
        "fruit": "orange",
        "weight": "10"
    }
]';


$data_2 =
'[
    {
        "color": "red",
        "thorn": "no"
    },
    {
        "color": "green",
        "thorn": "yes"
    },
    {
        "color": "orange",
        "thorn": "no"
    }
]';

但我想组合这些数组,然后我有一个完整的数据是这样的:

$full_data = 
'[
    {
        "fruit": "apple",
        "weight": "15",
        "color": "red",
        "thorn": "no"
    },
    {
        "fruit": "durian",
        "weight": "50",
        "color": "green",
        "thorn": "yes"
    },
    {
        "fruit": "orange",
        "weight": "10",
        "color": "orange",
        "thorn": "no"
    }
]';

我试过array_splice()

for ($i=0; $i < count($data_2); $i++) { 
    array_splice($data_1[$i], 0, 0, $data_2[$i]);
}

但它返回 '0' 和 '1' 而不是原始键名...

'[
    {
        "fruit": "apple",
        "weight": "15",
        "0": "red",
        "1": "no"
    },
    {
        "fruit": "durian",
        "weight": "50",
        "0": "green",
        "1": "yes"
    },
    {
        "fruit": "orange",
        "weight": "10",
        "0": "orange",
        "1": "no"
    }
]';

我想把那个 '0' 和 '1' 替换成原来的键名

【问题讨论】:

  • 使用 array_merge 代替 array_splice 并将其分配给第一个数组或新数组。

标签: php arrays laravel array-splice


【解决方案1】:

使用array_merge 合并两个数组。

$full_data = [];
for ($i=0; $i < count($data_2); $i++) { 
    $full_data[$i] = array_merge($data_1[$i], $data_2[$i]);
}

【讨论】:

    【解决方案2】:

    很简单,你可以这样做

    1. 使用json_decode函数将两个数组格式json转换成两个php数组。
    2. 遍历其中一个并分别用两个数组的值填充$full_data
    3. 使用json_encode函数以json格式显示数组。
    // 1.
    $data1 = json_decode($data_1,true);
    $data2 = json_decode($data_2,true);
    
    // 2.
    $full_data = [];
    for ($i=0; $i < count($data1); $i++) { 
        $full_data[$i] = $data1[$i] + $data2[$i];
    }
    // 3. 
    echo(json_encode($full_data));
    /*
    [
     {"fruit":"apple","weight":"15","color":"red","thorn":"no"},
     {"fruit":"durian","weight":"50","color":"green","thorn":"yes"},
     {"fruit":"orange","weight":"10","color":"orange","thorn":"no"}
    ]
    */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-04
      • 2013-02-13
      • 2011-03-19
      • 2015-05-18
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多