簡體   English   中英

如何從php中的多維數組中獲取元素?

[英]how to get elements from multidimensional array in php?

我已經在 php 中編寫了一些代碼。 我有以下數組,但我無法獲得年份。

如何從數組中獲取年份,即值1891, 1908, 1916, 1918

$data = array( 
    1891 => [
        'year' => 
            [0 => 'ABC'],
        'count' =>1
    ],
    1908 => [
        'year' => 
            [0 => 'ABC'],
        'count' => 1
    ],
    1916 => [
        'year' => 
            [0 => 'XYZ'],
        'count' => 1
    ],
    1918 => [
        'year' => 
            [0 => 'PQR'],
        'count' => 1
    ],
    1923 => [
        'year' => 
            [0 => 'LMN'],
        'count' => 1
     ]

    );

根據您提供的array

foreach($array as $key => $value){
    $key // This will contain the year
    $value // This will contain the associated aray
}

我重建了數組,它是一個真正的數組數組(其中包含了一些數組)。 總的來說,我完全建議不要使用如此復雜的數據結構而不將其簡化或將其轉換為對象,因為它不適合消費。

簡化簡化簡化!

話雖如此,這是一種利用最終數據的方法:

foreach($data as $num_year=>$info){
    $letters = $info['year'][0]; // or
    $letters = reset($info['year']); // reset gets first element numbered or associative
    $count = $info['count'];
    echo $num_year.' '.$letters.' '.$count;
}

在此處查看它在清理和重建的陣列上運行並具有有效輸出: http : //ideone.com/b9Fg6V

暫無
暫無

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

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