Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

PHP: Get n-th item of an associative array

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:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use 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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...