//your array
$yourArray = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
您提到的条件只是构建两个数组,您可以将array_keys与接受搜索值的第二个参数一起使用
$array1 = array_keys($yourArray, '1');
$array2 = array_keys($yourArray, '2');
如果您不想使用 array_keys,请进行迭代
$array1 = array();
$array2 = array();
foreach($yourArray as $key=>$value){
//will always be 1 or 2, so an if-else is enought
if($value == 1){
$array1[] = $key;
} else {
$array2[] = $key;
}
}
就是这样。
检查this link 的array_keys
如果您有超过 2 个值,以下将起作用,并且可以在其他情况下重复使用
您想根据值对它们进行分组
$arrayOfValues = array_values($yourArray);
//this returns only the values of the array
$arrayOfUniqueValues = array_unique($arrayOfValues);
//this returns an array with the unique values, also with this u consider
//the posibility for more different values
//also u can get the unique values array on a single line
$arrayIfUniqueValues = array_unique(array_values($yourArray));
你要返回的数组
$theReturn = array();
foreach($arrayOfUniqueValues as $value ){
//what does this do?
//for each iteration it creates a key in your return array "$theReturn"
//and that one is always equal to the $value of one of the "Unique Values"
//array_keys return the keys of an array, and with the second parameter
//it acceps a search parameter, so the keys it return are the ones
//that matches the value, so here u are getting the array already made
$theReturn[$value] = array_keys($yourArray, $value);
}
在这种情况下,var_dump 将如下所示
array(2) {
[1]=>
array(4) {
[0]=>
int(156)
[1]=>
int(157)
[2]=>
int(159)
[3]=>
int(161)
}
[2]=>
array(2) {
[0]=>
int(158)
[1]=>
int(160)
}
}
希望我的回答对您有所帮助,我尝试从最短/最简单的开始组织解决方案。
编辑:
我忘了你也需要键值,至少在这个解决方案中,数组总是引用值,比如 $array1, $array2 或 $key 引用值,就像上一个解决方案中一样