简体   繁体   English

如何显示数组的特定项目

[英]how to show a specific item of an array

I have an array like this: 我有一个像这样的数组:

Array
(
    [47] => Array
        (
            [name1] => 
        )

    [43] => Array
        (
            [name2] => 
        )

    [53] => Array
        (
            [name3] => selected
        )

    [50] => Array
        (
            [name4] => 
        )

    [51] => Array
        (
            [name5] => 
        )

    [37] => Array
        (
            [name6] => 
        )

)

and I want to show the value of name1, name2, name3, name4, name5, name6. 我想显示name1,name2,name3,name4,name5,name6的值。 I tried with: 我尝试了:

for($i = 0; $i < 6; $i++){
    echo $array_object[$i] . "<br/>";
}

but it doesn't work. 但这不起作用。 How can I fix it? 我该如何解决? Thanks! 谢谢!

You can use the array_keys function to get the indexes and then use them numerically: 您可以使用array_keys函数获取索引,然后以数字方式使用它们:

$keys=array_keys($array_object);
for($i = 0; $i < 6; $i++){
    echo $array_object[$keys[$i]][{'name'.($i+1)}]."<br/>";
}

This will allow you to use index [0] even though it refers to index [47] based on your example data in the question. 即使您根据问题中的示例数据引用索引[47],也可以使用索引[0]。

While I haven't bothered to check if your data will always contain at least 6 entries (again based on the example code you posted) but if your loop exceeds the number of entries in your array you will get an undefined index error unless you check it first. 虽然我没有费心检查您的数据是否总是包含至少6个条目(同样基于您发布的示例代码),但是如果您的循环超过了数组中的条目数量,除非您进行检查,否则将得到未定义的索引错误首先。

use one of this examples: 使用以下示例之一:

foreach($elements AS $element) {
    foreach($element AS $key=>$value) {
        if(!preg_match('/^name[0-9]+/s', $key)) // match "nameNUM" style text
            continue;
        echo $value.'<br/>';
    }
}

or 要么

foreach($elements AS $element) {
    for($i=1; $i<=6; $i++) {
        if(!isset($element['name'.$i])) 
            continue;
        echo $value.'<br/>';
    }
}

or 要么

$accepted_values = array('name1','name2','name3','name4','name5','name6');
foreach($elements AS $element) {
    foreach($element AS $key=>$value) {
        if(!in_array($key, $accepted_values)) 
            continue;
        echo $value.'<br/>';
    }
}

If your array is not sorted you need to create a (really long and bad) loop. 如果您的数组未排序,则需要创建(确实很长很糟糕)循环。

foreach($array_object as $subArray){
   foreach ($subArray as $elem){
      echo ($elem);
   }
}

Please consider to simplify your array because with huge amount of data, it's going to be so long. 请考虑简化您的数组,因为要处理大量数据,这将需要很长时间。

foreach ($array_object AS $entry) {
    foreach($entry AS $key=>$val) {
        echo $val.'<br />';
    }
}

Try with array_values is simple: 尝试使用array_values很简单:

$array_object= array_values($array_object);

for($i = 0; $i < count($array_object); $i++)
{
    echo $array_object[$i]['name']."<br/>";
}

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

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