gpt4 book ai didi

PHP—array_merge_recursive() - 相同键没有数组

转载 作者:搜寻专家 更新时间:2023-10-31 21:22:51 24 4
gpt4 key购买 nike

$php -a
php > $data1 = ['tag' => 'div', 'classes' => [1,2,3]];
php > $data2 = ['tag' => 'section', 'classes' => [2,3,4,5,6]];
php > $result = array_merge_recursive($data1, $data2);
php > print_r($result);
Array
(
[tag] => Array
(
[0] => div
[1] => section
)

[classes] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 2
[4] => 3
[5] => 4
[6] => 5
[7] => 6
)

)

Docs 中所述:

If the input arrays have the same string keys, then the values for these keys are merged together into an array[…]

PHP 中是否有一个现有的函数基本上做同样的事情,但没有将相同的键合并到一个数组中,以便覆盖值并保留键?

在这种情况下,我希望得到这样的结果:

Array
(
[tag] => section

[classes] => Array
(
[0] => 1
[1] => 2
[2] => 3
[5] => 4
[6] => 5
[7] => 6
)

)

关于@JustOnUnderMillions 的评论:

是的,我想知道,这不是我对这种功能的期望,我希望得到我正在寻找的结果。

最佳答案

你可以处理这个函数(递归和多数组):

<?php

$data1 = ['tag' => 'div', 'classes' => [1,2,3], 'foo' => ['bar' => [1,2], 'bar2' => 'foo']];
$data2 = ['tag' => 'section', 'classes' => [2,3,4,5,6], 'foo' => ['bar' => [2,3], 'bar3' => 'foo']];
$data3 = ['tag' => 'section', 'classes' => [7], 'foo' => ['bar' => [5], 'bar3' => 'foo2']];


print_r(custom_array_merge($data1, $data2, $data3));

function custom_array_merge() {
$arguments = func_get_args();
$datas = call_user_func_array('array_merge', $arguments);
foreach($datas as $key => $value) {
if(is_array($value)) {
$values = [];
foreach($arguments as $array) {
$values[] = isset($array[$key]) ? $array[$key] : [];
}

if(array_depth($value) === 1) {
$datas[$key] = array_unique(call_user_func_array('array_merge', $values));
}else {
$datas[$key] = call_user_func_array('custom_array_merge', $values);
}
}
}

return $datas;
}

function array_depth(array $array) {
$max_depth = 1;

foreach ($array as $value) {
if (is_array($value)) {
$depth = array_depth($value) + 1;

if ($depth > $max_depth) {
$max_depth = $depth;
}
}
}

return $max_depth;
}

关于PHP—array_merge_recursive() - 相同键没有数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42760439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com