简体   繁体   English

如何从php中的多维数组中获取元素?

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

I have written some code in php.我已经在 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 ?如何从数组中获取年份,即值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:根据您提供的array

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在此处查看它在清理和重建的阵列上运行并具有有效输出: http : //ideone.com/b9Fg6V

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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