简体   繁体   English

从数组中删除元素

[英]Remove element from an array

Hello I am looking for some help with removing an element from an array. 您好,我正在寻找有关从数组中删除元素的帮助。 My array $rooms holds events per rooms. 我的$rooms阵列包含每个房间的事件。 Each room has its own array and each event has its own array within the room array. 每个房间都有自己的数组,每个事件在房间数组中都有自己的数组。 I loop through $rooms and display the room ID and within this loop I loop through the events for that room and display their contents. 我遍历$rooms并显示房间ID,并在此循环中遍历该房间的事件并显示其内容。 I would like to remove the array for the event that has been displayed so I don't have spend time comparing it when I repeat the same loop. 我想删除已显示事件的数组,因此当我重复同一循环时,我没有花时间比较它。

Below is an example of the process I am describing. 以下是我正在描述的过程的示例。 I know it makes no sense to delete the element in this logic as I am using foreach, but within my application the logic of the function requires it.. 我知道在使用foreach时删除此逻辑中的元素是没有意义的,但是在我的应用程序中,函数的逻辑需要它。

$rooms $房

array(3) 
{ 
  [1]=> array(2) 
    { 
       ["rid"]=> string(1) "1" 
       ["events"]=> array(0) 
         { } 
    } 
  [2]=> array(2) 
    { 
       ["rid"]=> string(1) "2" 
       ["events"]=> array(0) 
         { } 
    } 
  [3]=> array(2) 
    { 
       ["rid"]=> string(1) "3" 
       ["events"]=> array(2) 
         { 
           [0]=> array(7) 
             { 
               ["lname"]=> string(20) "xxxxxxxxxxxxxxxxxxxx" 
             } 
           [1]=> array(7) 
             { 
               ["lname"]=> string(10) "yyyyyyyyyy" 
             } 
          }  
      } 
}

loop

foreach ($rooms as $room):
   echo $room['rid'];
   foreach ($room['events'] as $event):
       echo $event['lname'];

If you could tell me where within the foreach I should put the code and how should the code look like that would be really great. 如果您能告诉我,我应该将代码放在foreach哪个位置,以及代码应该如何显示,那真的很棒。 I think it should be right after echo $event['lname'] , but I can't figure out how to locate the element that is displayed so I can unset it.. 我认为应该在echo $event['lname'] ,但是我不知道如何找到显示的元素,因此可以取消设置。

Thank you all for reading, looking forward to your replies. 谢谢大家阅读,期待您的答复。

You can simply unset the event after echoing it, but you'll need to reference it from $rooms, so you need to use the key's at each level. 您可以在回显事件后简单地取消设置该事件,但是您需要从$ rooms中引用该事件,因此您需要在每个级别使用键。 Try this: 尝试这个:

foreach($rooms as $i => $room) {
    echo $room['rid'];
    foreach($room['events'] as $j => $event) {
        echo $event['lname'];
        unset($rooms[$i]['events'][$j]);
    }
}

You can see an example of it working here . 您可以在此处查看其工作示例。

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

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