我有这个数组
数组(
[0] => Array ( [0] => stdClass Object ( [id] => 226 [user_id] => 1 [name] => Eden Corner Tub by Glass - $2099 ) [1] => stdClass Object ( [id] => 225 [user_id] => 1 [name] => Blue Quilted Leather Jacket by Minusey - $499 ) [2] => stdClass Object ( [id] => 222 [user_id] => 1 [name] => Darling New Bathtub by Duravit - $6300 ) ) [1] => Array ( [0] => stdClass Object ( [id] => 226 [user_id] => 1 [name] => Eden Corner Tub by Glass - $2099 ) [1] => stdClass Object ( [id] => 229 [user_id] => 1 [name] => Batman Tumbler Golf Cart - $50000 ) [2] => stdClass Object ( [id] => 228 [user_id] => 1 [name] => Swirlio Frozen Fruit Dessert Maker - $60 ) ) )
我有一系列产品,我需要确保它们是独一无二的。 需要通过id使这个数组唯一。这些数组是通过推送值生成的。
我现在试图解决这个问题超过一个星期了,但是我没办法解决这个问题。我知道它应该很容易......但无论如何 - 我不明白:D
答案 0 :(得分:1)
试试这个:
$array = array(
0 => array(
"name" => "test",
"id" => 4
),
1 => array(
"name" => "test2",
"id" => 152
),
2 => array(
"name" => "test2",
"id" => 152
)
);
$newArray = array();
foreach($array as $value) {
$newArray[$value['id']]['name'] = $value['name'];
$newArray[$value['id']]['id'] = $value['id'];
}
答案 1 :(得分:0)
foreach($array as $key=>$inner_array)
{
foreach($array as $key_again=>$array_again)
{
if($key != $key_again)
{
if($inner_array['name'] != $array_again['name'] AND $inner_array['id'] != $array_again['id'])
{
//its okay
}
else
{
unset($array[$key]);
}
}
}
}
答案 2 :(得分:0)
不确定如何生成数组,但是,如果您可以更改它,则可以直接将数组键设置为ID并检查ID是否已设置。
否则,您可以执行以下操作:
$unique = array();
foreach( $array as $values ) {
if( ! isset( $unique[$values['id']] ) ) {
$unique[$values['id']] = $values;
}
}
答案 3 :(得分:0)
这将使您的数组独一无二:
$array = array(
0 => array(
"name" => "test",
"id" => 4
),
1 => array(
"name" => "test2",
"id" => 152
),
2 => array(
"name" => "test2",
"id" => 152
) );
$result = array();
$index = array();
foreach($array as $i => $elem) {
if(!isset($index[$elem['id']])) {
$result[$i] = $elem;
$index[$elem['id']] = 1;
}
}
echo var_export($result);
输出:
array (
0 =>
array (
'name' => 'test',
'id' => 4,
),
1 =>
array (
'name' => 'test2',
'id' => 152,
),
)
答案 4 :(得分:0)
这会奏效。它可以被认为比for
循环更干净,但我不确定性能。
$array = [
[ "name" => "test", "id" => 4 ],
[ "name" => "test2", "id" => 152 ],
[ "name" => "test2", "id" => 152 ]
];
array_walk($array, function(&$item, $idx) use($array){
$matches = array_slice(array_keys($array, $item), 1);
if (in_array($idx, $matches)) {
$item = false;
}
});
$array = array_filter($array);
修改由于您更新了要使用的数据集,因此您需要将其展平1级:
$array = call_user_func_array('array_merge', $array);