如何获取具有特定值的数组的关联索引

时间:2012-05-31 13:08:49

标签: php associative-array

    {
    [2012-05-23] => 1
    [2012-05-24] => 1
    [2012-05-25] => 1
    [2012-05-26] => 1
    [2012-05-27] => 1
    [2012-05-28] => 11
    [2012-05-29] => 11
    [2012-05-30] => 12
    }

例如这是我的数组,我只想获得数值大于10的数组的索引

所以在这种情况下答案必须听起来像那样

    {
    [0] => 2012-05-28
    [1] => 2012-05-29
    [2] => 2012-05-30
     }

6 个答案:

答案 0 :(得分:2)

像这样的人!

$new_array = array();
foreach ($array as $r => $a)
{
    if ($a>10)
    $new_array[] = $r;
}

答案 1 :(得分:0)

$array=//Your array in original post.
$newarray=array();
foreach ($array as $key=>$val) {
    if ($key>10) {
        $newarray[]=$key;
    }
}    

答案 2 :(得分:0)

如果$array是您的第一个阵列:

$new_array = array();
foreach($array as $key => $value) {
    if( $value > 10 ) {
        $new_array[] = $key;
    }
}

答案 3 :(得分:0)

试试这个(假设<pre>中的数组被称为$dates):

$result = array();
foreach($dates as $date => $value) {
    if($value > 10) $result[] = $date;
}

print_r($result);

答案 4 :(得分:0)

$testData = array ('2012-05-23' => 1,
                   '2012-05-24' => 1, 
                   '2012-05-25' => 1,
                   '2012-05-26' => 1, 
                   '2012-05-27' => 1, 
                   '2012-05-28' => 11, 
                   '2012-05-29' => 11, 
                   '2012-05-30' => 12,
                   );
$testNeedle = 10;

$result = array_filter($testData, 
                       function($arrayEntry) use ($testNeedle) {
                           return $arrayEntry > $testNeedle; 
                       }
);
$result = array_keys($result);

var_dump($result);

答案 5 :(得分:0)

此代码可以完成这项工作。

$array1 = array(
'2012-05-23' => 1,
'2012-05-24' => 1,
'2012-05-25' => 1,
'2012-05-26' => 1,
'2012-05-27' => 1,
'2012-05-28' => 11,
'2012-05-29' => 11,
'2012-05-30' => 12
);
$result = (array_keys(array_filter($array1, "select")));
function select($var)
{    return($var > 10);     }

您还可以在空数组中使用带有array_push的for循环来跳过回调函数。