使用 array_search() 到 return 与搜索字符串不匹配的第一个元素的键
Using array_search() to return key of first element that does not match the search string
如果有一种方法 array_search()
可以 return 第一次冲突的关键,就像我 运行
$key = array_search(40489, array_column($userdb, 'uid'));
在
Array
(
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
理想情况下 return
2
但我想要它 return
1
即第一个没有 'uid' = 40489 的元素
&
如果用 array_search()
做不到,有没有其他方法可以用循环来做?我试过 array_filter()
但无法正常工作。
如array_search
描述中所述:
Searches the array for a given value and returns the first corresponding key if successful
Returns the key for needle if it is found in the array, FALSE otherwise.
因此,您不能使用 array_search
来搜索不符合您需要的内容。而是编写您自己的函数,例如:
$array = []; // your array
foreach ($array as $key => $value) {
if ($value['uid'] != '40489') {
echo 'Key: ', $key;
// use `break` to stop iterating over
// array as you already found what you need
break;
}
}
如果有一种方法 array_search()
可以 return 第一次冲突的关键,就像我 运行
$key = array_search(40489, array_column($userdb, 'uid'));
在
Array
(
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
理想情况下 return
2
但我想要它 return
1
即第一个没有 'uid' = 40489 的元素 &
如果用 array_search()
做不到,有没有其他方法可以用循环来做?我试过 array_filter()
但无法正常工作。
如array_search
描述中所述:
Searches the array for a given value and returns the first corresponding key if successful
Returns the key for needle if it is found in the array, FALSE otherwise.
因此,您不能使用 array_search
来搜索不符合您需要的内容。而是编写您自己的函数,例如:
$array = []; // your array
foreach ($array as $key => $value) {
if ($value['uid'] != '40489') {
echo 'Key: ', $key;
// use `break` to stop iterating over
// array as you already found what you need
break;
}
}