簡體   English   中英

在多維數組中搜索鍵,然后在同一數組中找到特定的鍵

[英]Search multi-dimensional array for key then find specific key in same array

我終於在PHP中使用Gmail API破土動工,但是我無法從標題獲取“發件人”,“主題”和“時間”

我有一個看起來像這樣的數組,但是不斷:

Array
(
    [0] => Google_Service_Gmail_MessagePartHeader Object
        (
            [name] => Subject
            [value] => My Subject
            [modelData:protected] => Array
                (
                )

            [processed:protected] => Array
                (
                )

        )

    [1] => Google_Service_Gmail_MessagePartHeader Object
        (
            [name] => From
            [value] => John Doe
            [modelData:protected] => Array
                (
                )

            [processed:protected] => Array
                (
                )

        )

簡而言之,我只需要一種在['name'] => 'Date'時搜索數組的方法,然后就需要將['value']鍵中的內容存儲在變量中,以便稍后回顯。 我應該為此使用array_search之類的方法還是有更好的方法?

如果您不關心標題順序(99%的客戶不會),則可以將其從:(名稱,值)列表轉換為名稱的Map / Dict => List <Value>。 對於大多數標頭,您關心的是列表中只有一個值,但這會使從/主題/到標頭的獲取變得微不足道。

在python中將是:

headers = {}
for header in header_list:
  if header['name'] not in headers:
    headers['name'] = []
  headers['name'].append(header['value'])

最簡單的方法是遍歷數組並檢查name屬性值:

$date_value = '';
foreach ($headers as $header) {
    if ('Date' == $header->name) {
        $date_value = $header->value;
        break;
    }
}
var_dump($date_value);

這里$headers是您的數組。

// Grab only those elements of the array where the items ["name"] key is Date  
$b=array_filter($array,function($x){if ($x["name"]=="Date") return true; else return false;});
// Now $b is an array containing all elements of $a that are dates

// Then, echo each one of $b's "value"  
array_walk($b,function($k,$v){echo $b[$k]["value"];});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM