我需要在一个数组数组中搜索一个关键字,一旦成功返回与包含它的所有数组相关的所有信息。
这是数组的样子
Array
(
[#10-CH-L/W] => Array
(
[0] => 278.00
[1] => HIGH COLLAR LOCK WASHER
[2] => NUTBLT
)
[#16S-NUTS] => 6.00
[#16S-SLEEVES] => 13.00
[#16SS-NUTS] => 1.00
[#16SS-SLEEVES] => 4.00
[#20S-NUTS] => 11.00
[#20S-SLEEVES] => 14.00
[#20SS-NUTS] => .00
[#20SS-SLEEVES] => .00
[#400-CLAMP] => Array
(
[0] => .00
[1] => DIXON HOSE CLAMP-3-1/2" OD
[2] => FITTST
)
[#8S-SLEEVES] => 5.00
[-006-BN70] => Array
(
[0] => 181.00
[1] => O-RING 1/8 X 1/4 X 1/16
[2] => SEALS
)
[-006-VT75] => Array
(
[0] => .00
[1] => O-RING 1/8 X 1/4 X 1/16
[2] => SEALS
)
我在这里发现了一个类似的问题,并修改/尝试了代码,但是它仅从数组中返回一个匹配项,并将其密钥放入数组中。如果它返回所有关联数组的键,那会很好。 edit 似乎循环仅找到$ id的第一个匹配项,然后停止
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val[2] === $id) {
$keyarray[] = $key;
return $keyarray;
}
}
return null;
}
$id = searchForId('SEALS', $multi-array);
答案 0 :(得分:0)
function searchForId($id, $array) {
$keyarray = [];
foreach ($array as $key => $val) {
if (isset($val[2]) && $val[2] === $id) {
array_push( $keyarray, $key);
}
}
return $keyarray;
}
答案 1 :(得分:0)
@Sivabalan的回答正是我所需要的。我只是添加了一个片段,以使代码分割出与每个子数组关联的数据。我潜伏了好几年了。我在想什么?
function searchForId($id, $array) {
$keyarray = array();
foreach ($array as $key => $val) {
if (isset($val[2]) && $val[2] === $id) {
array_push( $keyarray, $key);
echo "$key | $val[0] | $val[1] | $val[2]";
}
}
return $keyarray;
}
$id = searchForId('needles', $haystack);