这是我的阵列:
array(4) {
["1"]=>
array(3) {
[0]=>
string(2) "01"
[1]=>
string(2) "02"
[2]=>
string(2) "03"
}
["2"]=>
array(2) {
[0]=>
string(2) "01"
[1]=>
string(2) "02"
}
["3"]=>
array(1) {
[0]=>
string(2) "01"
}
["4"]=>
array(1) {
[0]=>
string(2) "01"
}
}
我想打印最低密钥,但只能打印少于3个值的密钥。
echo min(array_keys($myarray));
给我结果:1
但是键1
已经有3个值,所以我需要的结果是2.如果每个键有3个值,则打印下一个键(在这种情况下为5)
我不知道该怎么做。我很满意每一个提示或建议。
答案 0 :(得分:2)
此函数遍历数组并查找值小于3的所有键。如果没有找到,则返回它发现的第一个,返回下一个键。
function getLowestKeyWithLessThan($yourArray, $number=3)
{
foreach ($yourArray as $key => $value) {
if (count($value) < $number)
return $key;
}
return count($yourArray) + 1;
}
如果我运行以下行:
print "Answer " . getLowestKeyWithLessThan($yourArray);
print "\nAnswer " . getLowestKeyWithLessThan($AllKeysHasThreeElements);
这给出了答案:
Answer 2 Answer 5
以下是我用来测试此数据的数据:
$yourArray = array(
"1"=> array(
'0' => "01",
'1' => "02",
'2' => "03",
),
"2"=> array(
'0' => "01",
'1' => "02",
),
"3"=> array(
'0' => "01",
),
"4"=> array(
'0' => "01",
),
);
$threeValues = array(
'0' => "01",
'1' => "02",
'2' => "03",
);
$AllKeysHasThreeElements = array(
"1"=> $threeValues,
"2"=> $threeValues,
"3"=> $threeValues,
"4"=> $threeValues,
);
当然,数据也可以这样写:
$threeValues = array("01", "02", "03");
$yourArray = array($threeValues, array("01", "02"), array("01"), array("01"));
$AllKeysHasThreeElements = array($threeValues,$threeValues,$threeValues,$threeValues);