简体   繁体   中英

how to get elements from multidimensional array in php?

I have written some code in php. I have below array, but I can't get the year.

How do I get the year from array ie the values 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
     ]

    );

Based on the array you provided:

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

I reconstructed the array, and it is a true array of arrays (with some arrays thrown in). Overall, I totally advise against using such a complex data structure without either simplifying or turning it into an object, because it doesn't lend itself well to consumption.

Simplify simplify simplify!

That being said, here is a way to utilize the final data:

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;
}

See it run on the cleaned-up and reconstructed array with valid output here: http://ideone.com/b9Fg6V

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM