简体   繁体   English

3d嵌套数组foreach语句问题

[英]3d nested array foreach statement issue

I have this array written below, and I know it isnt pretty, sorry. 我在下面写了这个数组,我知道它不漂亮,对不起。 I come to this array structure as it is the only way I could think of when dealing with my post request. 我来到这个数组结构,因为这是我在处理我的帖子请求时唯一能想到的方法。

$_POST = array("person" => array(
                                 [1] => array("id" => 1, "name" => "bob"), 
                                 [2] => array("id" => 2, "name" => "jim")
                                )
               );

I want to be able to pick "name" from certain "id", so below code is what I came up with. 我希望能够从某些“id”中选择“name”,所以下面的代码是我想出的。 In the example below, if person["id"] is equal to 1, retrieve its "name" which is "bob". 在下面的示例中,如果person [“id”]等于1,则检索其“名称”,即“bob”。

foreach ($_POST as $dataSet) {
    foreach ($dataSet as $person) {
        foreach ($person as $field => $value) {
            if ($person["id"] == 1) {
                echo $person["name"];
            }
        }
    }
}

The problem I am having is as I execute the code. 我遇到的问题是当我执行代码时。 the result is bobbob , 结果是bobbob

it seems like the code looped the if statement twice (same as the number of elements in the person array). 似乎代码循环了if语句两次(与person数组中的元素数相同)。 I know if I put break into the code, then it will solve it, but anyone know why it looped twice? 我知道如果我把密码放入代码中,那么它会解决它,但是有人知道它为什么循环两次? Maybe this will deepen my foreach and array understanding. 也许这会加深我对foreach和数组的理解。

There is no need to have third nested loop . 不需要第三个嵌套循环 Hope this one will be helpful. 希望这个会有所帮助。

Problem: In the third loop you were iterating over Persons: array("id" => 1, "name" => "bob") which have two keys. 问题:在第三个循环中,你迭代了Persons: array("id" => 1, "name" => "bob") ,它有两个键。 and you are checking only single static key $person["id"] , that's why it was printing twice. 并且您只检查单个静态键$person["id"] ,这就是它打印两次的原因。

Solution 1: 解决方案1:

Try this code snippet here 在此处尝试此代码段

<?php

ini_set('display_errors', 1);

$POSTData = array("person" => array(
        1 => array("id" => 1, "name" => "bob"),
        2 => array("id" => 2, "name" => "jim")
    )
);
foreach ($POSTData as $dataSet)
{
    foreach ($dataSet as $person)
    {
        if ($person["id"] == 1)
        {
            echo $person["name"];
        }
    }
}

Solution 2: 解决方案2:

Alternatively you can try this single line solution. 或者,您可以尝试这种单线解决方案。

Try this code snippet here 在此处尝试此代码段

 echo array_column($POSTData["person"],"name","id")[1];//here 1 is the `id` you want.

No need of third foreach 不需要第三个foreach

 <?php
   $mainArr = array("person" => array(
                        1 => array("id" => 1, "name" => "bob"), 
                        2 => array("id" => 2, "name" => "jim")
                           )
                   );
   foreach ($mainArr as $dataSet) {
       foreach ($dataSet as $person) {
         if ($person["id"] == 1) {
             echo $person["name"];
             break;
         }
       }
   }

   ?>

Live demo : https://eval.in/855386 现场演示: https//eval.in/855386

You must have seen the other answers, and they have already said that you dont need the 3rd loop . 你必须看到其他的答案,他们已经说过你不需要第三个循环 but still if you want to keep the third loop. 但仍然如果你想保持第三个循环。 you can use this code. 你可以使用这段代码。

foreach ($_POST as $dataSet) {

    foreach ($dataSet as $person) {

        foreach ($person as $field => $value) {

            if($value == 1){
                echo $person['name'];
            }

        }

    }

}

Although it's unclear why you need to do a POST in this fashion, here's how to get "bob" only once: 虽然目前还不清楚为什么你需要以这种方式进行POST,但这里是如何只获得一次“bob”:

<?php

$_POST = array("person" => array(
                                 1 => array("id" => 1, "name" => "bob"), 
                                 2 => array("id" => 2, "name" => "jim")
                                )
               );



$arr = array_pop($_POST);

foreach($arr as $a) {
  if ($a["id"] == 1) {
    echo $a["name"];
  }
}

Array_pop() is useful for removing the first element of the array whose value is an array itself which looks like this: Array_pop()对于删除数组的第一个元素非常有用,该数组的值是一个数组本身,如下所示:

array(2) {
  [1]=>
  array(2) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(3) "bob"
  }
  [2]=>
  array(2) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(3) "jim"
  }
}

When the if conditional evaluates as true which occurs only once then the name "bob" displays. 当if条件求值为true时,仅出现一次,则显示名称“bob”。

See live code . 查看实时代码

Alternatively, you could use a couple of loops as follows: 或者,您可以使用以下几个循环:

foreach ($_POST["person"] as $data) {
    foreach ($data as $value) {
        if ( $value == 1) {
            echo $data["name"],"\n";
        }
    }
}

See demo 演示

As you mentioned, I want to be able to pick name from certain id, : No need of nested looping for that. 正如您所提到的, 我希望能够从某个id中选择名称, :不需要嵌套循环。 You can do like this using array_column and array_search : 您可以使用array_columnarray_search执行此操作:

$data = array("person" => array(
        1 => array("id" => 1, "name" => "bob"),
        2 => array("id" => 2, "name" => "jim")
    )
);

// 1 is id you want to search for
$key = array_search(1, array_column($data['person'], 'id'));
echo $data['person'][$key + 1]['name']; // $key + 1 as you have started array with 1

Output: 输出:

bob

with foreach: 与foreach:

foreach ($data as $dataValue) {
    foreach ($dataValue as $person) {
        if ($person['id'] === 1) {
            echo $person["name"];
        }
    }
}

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

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