[英]PHP - Comparing two multidimensional arrays
我有兩個包含數據的數組,我需要比較兩個數組並創建一個最終數組..這是我的情況:
// grab a list of the folders
$folders = glob("../*",GLOB_ONLYDIR);
// create empty array's which will contain our data
$projects_data = array();
$folders_array = array();
// list the contents of the config file
$data = json_decode(file_get_contents('.my-config'), true);
// loop through our data file
foreach($data['web_app']['projects'] as $project) :
// update our projects data array
$projects_data[] = $project;
endforeach;
// loop through each folder on our localhost
foreach($folders as $folder) :
// update our folders array
$folders_array[] = array(
'folder' => basename($folder),
'last_modified' => filemtime($folder),
'dir_size' => dirsize($folder)
);
endforeach;
所以我有兩個數組..像這樣:
$projects_data array
Array
(
[0] => Array
(
[folder] => GitHub Clones
[last_modified] => 1379974689
[dir_size] => 6148
)
[1] => Array
(
[folder] => MagentoPlayground
[last_modified] => 1380336582
[dir_size] => 82340978
)
[2] => Array
(
[folder] => Projects
[last_modified] => 1380581312
[dir_size] => 5954
)
)
$folders_array array
Array
(
[0] => Array
(
[folder] => MagentoPlayground
[last_modified] => 1380336582
[dir_size] => 82340978
)
[1] => Array
(
[folder] => Projects
[last_modified] => 1380581312
[dir_size] => 5933
)
[2] => Array
(
[folder] => old
[last_modified] => 1371064970
[dir_size] => 63385844
)
)
我需要比較這兩個數組。如果頂部數組中存在一個數組,而第二個數組(Github Clones)中不存在,則需要刪除它。 如果底部數組中存在一個,而頂部數組(舊)中不存在,則需要添加它。 我想我將需要帶有新數據的第三個數組,但是我不確定如何構造它。
另外,如果兩個數組(MagentoPlayground)中都有兩個條目,則我需要新數組來使用底部數組中的數據。 底部的數組將具有最新的last_modified標記和目錄大小。
謝謝你的幫助。
我將使用您剛才提到的規則進行比較:
...並創建第三個也是最后一個數組。 由於第一個規則,您不妨通過數組B作為比較來解決該問題。
<?php
// multidimensional array key search (one deep)
function m_array_key_exists($key, $array) {
foreach($array as $subkey => $subvalue) {
if($subkey === $key)
return true;
if(is_array($subvalue)){
if(array_key_exists($key, subvalue))
return true;
}
}
return false;
}
?>
僅從這兩個規則看來,您也可以只使用第二個數組,因為如果兩個數組中都存在第二個數組,則可以保留它;如果B中不存在,則將其刪除,但無論如何都不會刪除它,並且如果它存在於B中但不存在於A中,則添加它,但它已經存在...
如上所示,使用m_array_key_exists來檢查比array_key_exists()更深的一級,如所示,數組中是否存在數組鍵。 如果您的規則不像我想象的那么簡單,聽起來像您想遍歷第二個數組,檢查數組鍵,應用特殊規則並將結果添加到第三個數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.