以下是数组和我尝试独特/合并的代码
$data['default_new'] = array_unique(array_merge($data['default'], $data['related']))
Array
(
[0] => Array
(
[keywords_id] => 8
[keyword] => Curling
[parent_id] => 5
[count] => 0
)
)
Array
(
[0] => Array
(
[keywords_id] => 8
[keyword] => Curling
[parent_id] => 5
[count] => 0
)
[1] => Array
(
[keywords_id] => 10
[keyword] => Catchers
[parent_id] => 6
[count] => 0
)
[2] => Array
(
[keywords_id] => 16
[keyword] => CES 2013
[parent_id] => 3
[count] => 0
)
)
它给了我一个字符串错误的数组:
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: models/content_model.php
Line Number: 29
我之前遇到过这个独特的问题并且之前合并过并且从未修复过它!
我正在使用codeigniter
这里有关于我正在使用array_unique / merge的函数的更多信息:
public function results($data, $searched)
{
$page['searched'] = $searched;
$page['is_active'] = $this->logic_model->is_active();
$data2 = array();
$data2['default_new'] = array_unique(array_merge($data['default'],
$data['related']));
}
第29行是$data2['default_new'] = array_u
$data
参数包含,default
和regular
,可在上面看到。
vardump of data:
array(3) {
["active"]=>
array(2) {
["id"]=>
string(1) "5"
["keyword"]=>
string(6) "Sports"
}
["related"]=>
array(1) {
[0]=>
array(4) {
["keywords_id"]=>
string(1) "8"
["keyword"]=>
string(7) "Curling"
["parent_id"]=>
string(1) "5"
["count"]=>
string(1) "0"
}
}
["default"]=>
array(3) {
[0]=>
array(4) {
["keywords_id"]=>
string(1) "8"
["keyword"]=>
string(7) "Curling"
["parent_id"]=>
string(1) "5"
["count"]=>
string(1) "0"
}
[1]=>
array(4) {
["keywords_id"]=>
string(2) "10"
["keyword"]=>
string(8) "Catchers"
["parent_id"]=>
string(1) "6"
["count"]=>
string(1) "0"
}
[2]=>
array(4) {
["keywords_id"]=>
string(2) "16"
["keyword"]=>
string(8) "CES 2013"
["parent_id"]=>
string(1) "3"
["count"]=>
string(1) "0"
}
}
}
答案 0 :(得分:1)
错误不是来自array_unique
或array_merge
函数调用。
问题在于您之前已将$data
定义为string
。
这应该解决它:
$data = array();
$data['default_new'] = array_unique(array_merge($data['default'], $data['related']))
答案 1 :(得分:1)
请在此处查看“备注”部分:http://us.php.net/array_unique#refsect1-function.array-unique-notes
您需要提出自己的算法来创建一个独特的多维数组。上面链接中的一些评论提出了实现此目的的各种方法,例如this one:
<?php
$values = array();
foreach($data as $d) {
$values[md5(serialize($d))] = $d;
}
sort($values);
?>
关于SO的相关问题:strange behavior of php array_unique和How do I use array_unique on an array of arrays?