PHP:获取关联数组的第 n 项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1997653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:35:45  来源:igfitidea点击:

PHP: Get n-th item of an associative array

phpassociative-array

提问by Nick Heiner

If you have an associative array:

如果你有一个关联数组:

Array
(
    [uid] => Marvelous
    [status] => 1
    [set_later] => Array
        (
            [0] => 1
            [1] => 0
        )

    [op] => Submit
    [submit] => Submit
)

And you want to access the 2nd item, how would you do it? $arr[1]doesn't seem to be working:

你想访问第二个项目,你会怎么做?$arr[1]似乎不起作用:

foreach ($form_state['values']['set_later'] as $fieldKey => $setLater) {
    if (! $setLater) {
        $valueForAll = $form_state['values'][$fieldKey];
        $_SESSION[SET_NOW_KEY][array_search($valueForAll, $form_state['values'])] = $valueForAll; // this isn't getting the value properly
    }
}

This code is supposed to produce:

这段代码应该产生:

$_SESSION[SET_NOW_KEY]['status'] = 1

But it just produces a blank entry.

但它只会产生一个空白条目。

回答by nickf

Use array_slice

array_slice

$second = array_slice($array, 1, 1, true);  // array("status" => 1)

// or

list($value) = array_slice($array, 1, 1); // 1

// or

$blah = array_slice($array, 1, 1); // array(0 => 1)
$value = $blah[0];

回答by Perry Munger

I am a bit confused. Your code does not appear to have the correct keys for the array. However, if you wish to grab just the second element in an array, you could use:

我有点困惑。您的代码似乎没有正确的数组键。但是,如果您只想获取数组中的第二个元素,则可以使用:

$keys = array_keys($inArray);
$key = $keys[1];
$value = $inArray[$key];

However, after considering what it appears you're trying to do, something like this might work better:

但是,在考虑了您正在尝试做的事情之后,这样的事情可能会更好:

$ii = 0;
$setLaterArr = $form_state['values']['set_later'];
foreach($form_state['values'] as $key => $value) {
    if($key == 'set_later')
        continue;
    $setLater = $setLaterArr[$ii];
    if(! $setLater) {
        $_SESSION[SET_NOW_KEY][$key] = $value;
    }
    $ii ++;
}

Does that help? It seems you are trying to set the session value if the set_later value is not set. The above code does this. Instead of iterating through the inner array, however, it iterates through the outer array and uses an index to track where it is in the inner array. This should be reasonably performant.

这有帮助吗?如果未设置 set_later 值,您似乎正在尝试设置会话值。上面的代码就是这样做的。然而,它不是遍历内部数组,而是遍历外部数组并使用索引来跟踪它在内部数组中的位置。这应该是合理的性能。

回答by leepowers

You can use array_sliceto get the second item:

您可以使用array_slice来获取第二个项目:

$a= array(
 'hello'=> 'world',
 'how'=> 'are you',
 'an'=> 'array',
);

$second= array_slice($a, 1, 1, true);
var_dump($second);

回答by Sam Carlton

Here's a one line way to do it with array_sliceand current

这是使用array_slicecurrent的一种单行方式

$value = current(array_slice($array, 1, 1)); // returns value only

回答by Manchumahara

/**
         * Get nth item from an associative array
         * 
         * 
         * @param     $arr
         * @param int $nth
         *
         * @return array
         */
        function getNthItemFromArr($arr, $nth = 0){
            $nth = intval($nth);
            if(is_array($arr) && sizeof($arr) > 0 && $nth > 0){
                $arr = array_slice($arr,$nth-1, 1, true);
            }
            return $arr;
        }//end function getNthItemFromArr

回答by metrobalderas

Every one of the responses here are focused on getting the second element, independently on how the array is formed.

这里的每个响应都集中在获取第二个元素上,与数组的形成方式无关。

If this is your case.

如果这是你的情况。

Array
(
    [uid] => Marvelous
    [status] => 1
    [set_later] => Array
        (
            [0] => 1
            [1] => 0
        )

    [op] => Submit
    [submit] => Submit
)

Then you can get the value of the second element via $array['status'].

然后你可以通过$array['status'].

Also this code

还有这个代码

foreach ($form_state['values']['set_later'] as $fieldKey => $setLater) {
    if (! $setLater) {
        $valueForAll = $form_state['values'][$fieldKey];
        $_SESSION[SET_NOW_KEY][array_search($valueForAll, $form_state['values'])] = $valueForAll; // this isn't getting the value properly
    }
}

I don't understand what are you trying to do, care to explain?

我不明白你想做什么,介意解释一下吗?

回答by Elise van Looij

If the array you provide in the first example corresponds to $form_state then

如果您在第一个示例中提供的数组对应于 $form_state 那么

$form_state['values']['set_later'][1]

will work.

将工作。

Otherwise

除此以外

$i = 0;
foreach ($form_state['values']['set_later'] as $fieldKey => $setLater) {
    if ($i == 1) {
        $valueForAll = $form_state['values'][$fieldKey];
        $_SESSION[SET_NOW_KEY][$fieldKey] = $setLater;
        continue;
    }
    $i++;
}