在PHP中按键匹配数组值
我有一系列的项目:在PHP中按键匹配数组值,php,arrays,Php,Arrays,我有一系列的项目: array( [0] => array( 'item_no' => 1 'item_name' => 'foo ) [1] => array( 'item_no' => 2 'item_name' => 'bar' ) ) etc. etc. 我正在从第三方来源获取另一个阵列,需要删除不在第一个阵列中的项目 array( [0] => array( 'item_no' =&
array(
[0] => array(
'item_no' => 1
'item_name' => 'foo
)
[1] => array(
'item_no' => 2
'item_name' => 'bar'
)
) etc. etc.
我正在从第三方来源获取另一个阵列,需要删除不在第一个阵列中的项目
array(
[0] => array(
'item_no' => 1
)
[1] => array(
'item_no' => 100
) # should be removed as not in 1st array
如何使用第二个数组中的每个项搜索第一个数组,如(在伪代码中):
如果'item_no'==x在第一个数组中,请继续,否则将其从第二个数组中删除。如果您的键实际上不是数组的键而是值,则可能需要进行线性搜索:
foreach ($itemsToRemove as $itemToRemove) {
foreach ($availableItems as $key => $availableItem) {
if ($itemToRemove['item_no'] === $availableItem['item_no']) {
unset($availableItems[$key]);
}
}
}
如果项_no也是数组项的键,则肯定会更容易,如:
$availableItems = array(
123 => array(
'item_no' => 123,
'item_name' => 'foo'
),
456 => array(
'item_no' => 456,
'item_name' => 'bar'
)
);
使用此功能,您可以使用单个foreach
并通过其键删除项目:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$itemToRemove['item_no']]);
}
您可以使用以下方法来构建项_no到实际数组键的映射:
$map = array();
foreach ($availableItems as $key => $availableItem) {
$map[$availableItems['item_no']] = $key;
}
然后,您可以使用以下操作来使用映射删除相应的数组项:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$map[$itemToRemove['item_no']]]);
}
如果不将键存储在元素中,而是将其存储为数组键(也就是说,您将使用“item_no=>item_data”形式的数组),则所有这些都会更容易:
您还可以执行以下操作:
$my_array =array(
0 => array( 'item_no' => 1,'item_name' => 'foo'),
1 => array( 'item_no' => 2,'item_name' => 'bar')
);
$thrid_party_array = array(
0 => array( 'item_no' => 1),
1 => array( 'item_no' => 100),
);
$temp = array(); // create a temp array to hold just the item_no
foreach($my_array as $key => $val) {
$temp[] = $val['item_no'];
}
// now delete those entries which are not in temp array.
foreach($thrid_party_array as $key => $val) {
if(!in_array($val['item_no'],$temp)) {
unset($thrid_party_array[$key]);
}
}
非常感谢,这一个非常适合我的应用程序,尤其是我以后需要一个“item\u no”数组。
// That's all there is to it
return array_key_intersect($theirArray, $myArray);
$my_array =array(
0 => array( 'item_no' => 1,'item_name' => 'foo'),
1 => array( 'item_no' => 2,'item_name' => 'bar')
);
$thrid_party_array = array(
0 => array( 'item_no' => 1),
1 => array( 'item_no' => 100),
);
$temp = array(); // create a temp array to hold just the item_no
foreach($my_array as $key => $val) {
$temp[] = $val['item_no'];
}
// now delete those entries which are not in temp array.
foreach($thrid_party_array as $key => $val) {
if(!in_array($val['item_no'],$temp)) {
unset($thrid_party_array[$key]);
}
}