我有以下内容:
[6199]=>
array(12) {
["Origin"]=>
array(3) {
["name"]=>
array(1) {
[0]=>
string(4) "Cuba"
}
["slug"]=>
array(1) {
[0]=>
string(27) "cuabn-havana-habanos-cigars"
}
["id"]=>
array(1) {
[0]=>
int(0)
}
}
["Filler"]=>
array(3) {
["name"]=>
array(2) {
[0]=>
string(9) "Dominican"
[1]=>
string(10) "Nicaraguan"
}
["slug"]=>
array(2) {
[0]=>
string(9) "dominican"
[1]=>
string(10) "nicaraguan"
}
["id"]=>
array(2) {
[0]=>
int(0)
[1]=>
int(1)
}
}
}
[6192]=>
array(11) {
["Origin"]=>
array(3) {
["name"]=>
array(1) {
[0]=>
string(9) "Nicaragua"
}
["slug"]=>
array(1) {
[0]=>
string(27) "nicaraguan-new-world-cigars"
}
["id"]=>
array(1) {
[0]=>
int(0)
}
}
["Filler"]=>
array(3) {
["name"]=>
array(2) {
[0]=>
string(9) "Java"
[1]=>
string(10) "Nicaraguan"
}
["slug"]=>
array(2) {
[0]=>
string(9) "java"
[1]=>
string(10) "nicaraguan"
}
["id"]=>
array(2) {
[0]=>
int(0)
[1]=>
int(1)
}
}
}
我的预期输出是:
array(12) {
["Origin"]=>
array(3) {
["name"]=>
array(1) {
[0]=>
string(4) "Cuba".
[1]=>
string(9) "Nicaragua"
}
["slug"]=>
array(1) {
[0]=>
string(27) "cuabn-havana-habanos-cigars",
[0]=>
string(27) "nicaraguan-new-world-cigars"
}
["id"]=>
array(1) {
[0]=>
int(0)
}
}
["Filler"]=>
array(3) {
["name"]=>
array(2) {
[0]=>
string(9) "Dominican"
[1]=>
string(10) "Nicaraguan"
[2]=>
string(9) "Java"
}
["slug"]=>
array(2) {
[0]=>
string(9) "dominican"
[1]=>
string(10) "nicaraguan"
[3]=>
string(9) "java"
}
["id"]=>
array(2) {
[0]=>
int(0)
[1]=>
int(1)
}
}
了解它如何消除欺骗并合并每个维护“origin”键的数组。 我试过了:
foreach ($resultterms as $keyname => $valuename){
foreach ($valuename as $keysub => $valuesub) {
foreach($valuesub['name'] as $keysubsub => $valuesubsub){
# code...
$prods_atts[$keysub]['name'][$keysubsub] = $valuesubsub;
$prods_atts[$keysub]['slug'][$keysubsub] = $valuesub['slug'][$keysubsub];
$prods_atts[$keysub]['id'][$keysubsub] = $valuesub['id'][$keysubsub];
}
}
}
其中$resultterms
是原始数组,但它不起作用。我想知道是否有一个很好的PHP函数我可以用它来合并这些而不是为每个循环嵌套这么多?
答案 0 :(得分:2)
我相信你只是在寻找array_merge_recursive。
call_user_func_array('array_merge_recursive', array_values($prod_atts));
call_user_func_array
允许将数组转换为参数列表array_values
因为最后,你似乎想要摆脱数组的第一层为了试用它,您可以发布变量的var_export
而不是var_dump
吗?
echo(var_export($prod_atts, true));
答案 1 :(得分:1)
通过任何建议的方法合并您的数组。之后,您将获得重复的值。而且您只需要保存唯一的项目
$new = array_merge_recursive($resultterms['6199'], $resultterms['6192']);
foreach($new['Origin'] as &$item) { $item = array_unique($item); }
foreach($new['Filler'] as &$item) { $item = array_unique($item); }