У меня есть два многомерных массива. Первый из них:
Array
(
[0] => Array
(
[username] => J1
[fullname] => John1
)
[1] => Array
(
[username] => K1
[fullname] => Kate
)
[2] => Array
(
[username] => P1
[fullname] => Peter
)
[3] => Array
(
[username] => M1
[fullname] => Mary
)
)
and the second one is:
Array
(
[0] => Array
(
[username] => J1
[fullname] => John33
)
[1] => Array
(
[username] => L1
[fullname] => Lucas
)
[2] => Array
(
[username] => P1
[fullname] => Paul
)
)
Я хочу сравнить два массива, используя только их имя пользователя, чтобы получить элементы первого массива, которые не включены во второй массив (сравнивая только имена пользователей).
поэтому я хочу новый массив, как показано ниже:
Array
(
[0] => Array
(
[username] => K1
[fullname] => Kate
)
[1] => Array
(
[username] => M1
[fullname] => Mary
)
)
Любая помощь?? большое спасибо!!!
Вы можете сделать что-то подобное в PHP> = 5.5.0:
$result = array_diff_key(array_column($array1, null, 'username'),
array_column($array2, null, 'username')
);
Попробуйте перебрать один массив и сравнить его так:
$array_one = Array
(
[0] => Array
(
[username] => J1
[fullname] => John1
)
[1] => Array
(
[username] => K1
[fullname] => Kate
)
[2] => Array
(
[username] => P1
[fullname] => Peter
)
[3] => Array
(
[username] => M1
[fullname] => Mary
)
);
$array_two = Array
(
[0] => Array
(
[username] => J1
[fullname] => John33
)
[1] => Array
(
[username] => L1
[fullname] => Lucas
)
[2] => Array
(
[username] => P1
[fullname] => Paul
)
);
foreach($array_one as $key => $value) {
if($value['username'] == $array_two[$key]['username'])
// do something
else
// do something
}
$array1 = array(
"0" => Array(
"username" => "J1",
"fullname" => "John1"),
"1" => Array(
"username" => "K1",
"fullname" => "Kate"),
"2" => Array(
"username" => "P1",
"fullname" => "Peter"),
"3" => Array(
"username" => "M1",
"fullname" => "Mary")
);
$array2 = array(
"0" => Array(
"username" => "J1",
"fullname" => "John33"),
"1" => Array(
"username" => "L1",
"fullname" => "Lucas"),
"2" => Array(
"username" => "P1",
"fullname" => "Paul")
);
$newarr = array();
foreach( $array1 as $key => $val ) {
if($val['username'] != $array2[$key]['username']){
$newarr[] = $val;
}
}
echo '<pre>';print_r($newarr);echo '</pre>';
Выход :
Array
(
[0] => Array
(
[username] => K1
[fullname] => Kate
)
[1] => Array
(
[username] => M1
[fullname] => Mary
)
)