![](/img/trans.png)
[英]How can I compare two arrays and display differences for each key (multidimensional arrays)?
[英]How can I compare the differences of two arrays and output the key, which only exits in one array?
我有一個由文本文件創建的數組( $name_new
):
foreach ($properties as $key => $row) {
$name_new[] = $row['name'];
}
這是$name_new
的結果:
array(2) {
[0]=>
string(32) "john"
[1]=>
string(32) "frank"
}
我從mySQL數據庫創建的另一個數組:
$sql = "SELECT * FROM data;
$p = $pdo->prepare($sql);
$p->execute();
foreach ($pdo->query($sql) as $row) {
$name_orig[] = $row['name'];
}
這是$name_orig
的結果:
array(2) {
[0]=>
string(32) "john"
[1]=>
string(32) "sam"
}
我正在比較這兩個數組:
if ($name_new != $name_orig) {
$name_result = array_diff_assoc($name_orig, $name_new);
foreach($name_result as $r){
echo "This name is not matching: ".$r;
}
}
所以我的結果是:
這個名字不匹配:sam
我的問題是,我還需要在結果中輸入名稱的鍵。 但是此密鑰僅存在於文本文件中。
所以,如果我這樣寫:
foreach ($properties as $key => $row) {
$name_new[$key] = $row['name'];
}
這是$name_new[$key]
...
array(2) {
["123"]=>
string(32) "john"
["456"]=>
string(32) "frank"
}
...我知道了。 但是我怎樣才能把這個鑰匙連接到我的結果sam
我需要的結果是
此名稱與sam不匹配(密鑰:456)
請改進以下代碼
if ($name_new != $name_orig) {
$name_result = array_diff_assoc($name_orig, $name_new);
foreach($name_result as $k=> $r){
echo "This name is not matching: ".$r." and key:".$k;
}
}
希望這行得通
比較兩個數組時,只需將索引添加到您的foreach循環中即可達到目的:
foreach($name_result as $k => $r){
echo "This name is not matching: ".$r. "(Key:".$k.")";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.