我想要什么?从这个数组中,我们将其称为$forsend
:
array(3) {
[7493474]=>
array(6) {
["id"]=>
int(1414594)
["product_id"]=>
int(1)
["ins_type"]=>
string(4) "zzzz"
["phone"]=>
string(10) "1111111111"
["exam_date"]=>
string(10) "28.07.2018"
["status"]=>
int(1)
}
[7578595]=>
array(6) {
["id"]=>
int(1414969)
["product_id"]=>
int(1)
["ins_type"]=>
string(4) "zzzz"
["phone"]=>
string(10) "2222222222"
["exam_date"]=>
string(10) "28.07.2018"
["status"]=>
int(1)
}
[7583863]=>
array(6) {
["id"]=>
int(1415124)
["product_id"]=>
int(1)
["ins_type"]=>
string(4) "zzzz"
["phone"]=>
string(10) "1111111111"
["exam_date"]=>
string(10) "28.07.2018"
["status"]=>
int(1)
}
}
我想删除这些与同一部手机相同的记录(在这种情况下为1111111111,但可以有多个相同的记录),没有第一个记录 ,结果将是:
array(2) {
[7493474]=>
array(6) {
["id"]=>
int(1414594)
["product_id"]=>
int(1)
["ins_type"]=>
string(4) "zzzz"
["phone"]=>
string(10) "1111111111"
["exam_date"]=>
string(10) "28.07.2018"
["status"]=>
int(1)
}
[7578595]=>
array(6) {
["id"]=>
int(1414594)
["product_id"]=>
int(1)
["ins_type"]=>
string(4) "ГО"
["phone"]=>
string(10) "2222222222"
["exam_date"]=>
string(10) "28.07.2018"
["status"]=>
int(1)
}
}
我尝试了什么? ..这段代码:
foreach($forsend as $x) {
var_dump($x);
$foundKey = array_search($x['phone'], array_column($forsend, 'phone'));
unset($forsend[$foundKey]);
}
目前它不起作用,它找到了密钥,但没有将其删除,我也不知道为什么。
答案 0 :(得分:1)
您可以尝试使用此代码,如果我正确理解您的需求,它应该可以工作。
<?php
$phones = [];
$final = [];
foreach($forsend as $key => $record) {
if(!isset($phones[$record['phone']]))
//reversing - now we have an array which is arranged using phone number as a key,
//meaning that only one record can exist with the same number
$phones[$record['phone']] = $key;
else
//if the record is repeated, remove the previous instance, and do not add this one
//to the array
unset($phones[$record['phone']]);
}
foreach($phones as $phone){
//reversing again, getting the format that was used before, from $phone the key of the
//top array is returned and using that key the data is taken from
//$forsend and put to final
$final[$phone] = $forsend[$phone];
}
print_r($final);
要保留具有相同手机的第一个元素,只需删除else
中的if
子句,该子句就足够了:
<?php
$phones = [];
$final = [];
foreach($forsend as $key => $record) {
if(!isset($phones[$record['phone']]))
$phones[$record['phone']] = $key;
}
foreach($phones as $phone){
$final[$phone] = $forsend[$phone];
}
print_r($final);