簡體   English   中英

使用PHP從API獲取多維數組中的特定值

[英]Get an specific value in a multidimensional array from an API with PHP

我正在嘗試獲取數組的值,但是我能做的是

$characters = $array['data']['results'];

為什么我不能像做$characters['stories']這樣深入數組呢?

以圖片為例。 因此,如果我想在頁面上顯示該系列的名稱,該如何賦予該值? 我知道這是一個初學者的問題。 一位同事告訴我使用array_key_exists,但是在stackoverflow的其他答案中,人們建議其他事情,是否有獨特的方法或更正確的方法呢? 順便說一句,我試圖調整答案,但是沒有用。

具有API結果的數組

如您在圖像中所見, results之后有一個名為0的屬性。 為了獲取stories ,您需要使用:

$characters = $array['data']['results'];
$characters[0]['stories'];

如果有更多類似的數字索引,並且您想遍歷每個數字索引,則必須使用forforeach循環。

示例:( 使用foreach

foreach ($characters as $character) {
    # Print the stories array for each character.
    print_r($character['stories']);
}

示例:( for

for ($index = 0; $index < count($characters); $index++) {
    # Print the stories array for each character.
    print_r($characters[$index]['stories']);
}

暫無
暫無

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

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