从另一个键的值中获取键值

时间:2015-05-25 18:50:17

标签: php arrays multidimensional-array associative-array

我正在尝试解析PHP curl函数使用的Netscape HTTP Cooke File

我正在使用this parser返回如下数组:

Array
(
    [0] => Array
        (
            [domain] => REDACTED
            [flag] => FALSE
            [path] => /
            [secure] => FALSE
            [expiration] => 2016-05-23 03:27:19
            [name] => csrftoken
            [value] => REDACTED
        )

    [1] => Array
        (
            [domain] => #HttpOnly_REDACTED
            [flag] => FALSE
            [path] => /
            [secure] => FALSE
            [expiration] => 2015-06-08 03:27:17
            [name] => sessionid
            [value] => REDACTED
        )

    [2] => Array
        (
            [domain] => REDACTED
            [flag] => FALSE
            [path] => /
            [secure] => FALSE
            [expiration] => 1969-12-31 09:00:00
            [name] => PHPSESSID
            [value] => REDACTED
        )

)

我需要在这里获得sessionid。问题是,我不能只使用$ array [1] ['value'],因为数组的数量及其位置不固定。我所知道的只是$ array [?] ['name'] ==“sessionid”。

1 个答案:

答案 0 :(得分:1)

这应该有效。

<?php

// this is array returned to you from parser
$array = ...;

foreach ($array as $number => $row) {
    if ($row['name'] == 'sessionid') {
        $index = $number;
        break;
    }        
}

if (isset($number)) {
    $sessionID = $array[$index];
} else {
    echo "nothing found";
}

// now you can use $sessionID['expiration'] etc