我在PHP中有这个数组:
array(
[0] => array( 'username' => 'user1' )
[1] => array( 'username' => 'user2' )
)
Run Code Online (Sandbox Code Playgroud)
如果我有"用户名"字符串,我怎样才能将索引值作为数字?
例如,如果我有'user1',我怎么能得到0?
Dan*_*ker 28
看一下array_search.
从PHP帮助文件:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
Run Code Online (Sandbox Code Playgroud)
nic*_*ckf 25
如果您有一个2D数组,就像在您的示例中一样,您需要稍微自定义一些内容:
function array_search2d($needle, $haystack) {
for ($i = 0, $l = count($haystack); $i < $l; ++$i) {
if (in_array($needle, $haystack[$i])) return $i;
}
return false;
}
$myArray = array(
array( 'username' => 'user1' ),
array( 'username' => 'user2' )
);
$searchTerm = "user1";
if (false !== ($pos = array_search2d($searchTerm, $myArray))) {
echo $searchTerm . " found at index " . $pos;
} else {
echo "Could not find " . $searchTerm;
}
Run Code Online (Sandbox Code Playgroud)
如果您只想搜索一个特定字段,可以将函数更改为以下内容:
function array_search2d_by_field($needle, $haystack, $field) {
foreach ($haystack as $index => $innerArray) {
if (isset($innerArray[$field]) && $innerArray[$field] === $needle) {
return $index;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
这很简单
private function getArrayKey($haystack, $needle)
{
foreach($haystack as $key => $product)
{
if ($product['id'] === $needle)
return $key;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)