如果爲特定鍵找到重複值,我想從多維數組中刪除一個子數組。 answer(s) here根本沒有工作。但是,answer here適用於大量數組,但速度會變慢。尋找更清潔,更快速的解決方案。如果某個鍵的值重複,則刪除子數組
例PHP陣列
$args = array();
$args[] = array(
'section' => array(
'id' => 'section1',
'name' => 'Section 1',
),
'name' => 'Shortcode Name',
'action' => 'shortcodeaction',
'icon' => 'codeicon',
'image' => 'codeimage',
);
$args[] = array(
'section' => array(
'id' => 'section2',
'name' => 'Section 2',
),
'name' => 'Shortcode2 Name',
'action' => 'shortcodeaction2',
'icon' => 'codeicon2',
'image' => 'codeimage2',
);
$args[] = array(
'section' => array(
'id' => 'section3',
'name' => 'Section 3',
),
'name' => 'Shortcode3 Name',
'action' => 'shortcodeaction3',
'icon' => 'codeicon3',
'image' => 'codeimage3',
);
$args[] = array(
'section' => array(
'id' => 'section1',
'name' => 'Section 4',
),
'name' => 'Shortcode4 Name',
'action' => 'shortcodeaction4',
'icon' => 'codeicon4',
'image' => 'codeimage4',
);
$args[] = array(
'section' => array(
'id' => 'section5',
'name' => 'Section 5',
),
'name' => 'Shortcode5 Name',
'action' => 'shortcodeaction5',
'icon' => 'codeicon5',
'image' => 'codeimage5',
);
$sections = array();
foreach ($args as $arg) {
$sections[] = $arg['section'];
}
並且,print_r($sections)
結果。
Array
(
[0] => Array
(
[id] => section1
[name] => Section 1
)
[1] => Array
(
[id] => section2
[name] => Section 2
)
[2] => Array
(
[id] => section3
[name] => Section 3
)
[3] => Array
(
[id] => section1
[name] => Section 4
)
[4] => Array
(
[id] => section5
[name] => Section 5
)
)
兩個Array[0]
和Array[3]
具有用於鍵id
相同的值,爲此整個Array[3]
在我的情況下,以避免重複去除。
雖然這對我有用,但是當數組爲100或更多時,它會變得非常慢。
$knownIds = array();
foreach($sections AS $key=>$item) {
if(array_key_exists($item['id'], $knownIds) === true) {
unset($sections[$key]);
} else {
$knownIds[$item['id']] = $key;
}
}
$sections = array_values($sections);
試了幾個答案在這裏StackOverflow上(包括this),但沒有人幫助我的情況。
感謝
的可能的複製[如何從多維刪除重複值數組在PHP中](http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php) – Epodax