简体   繁体   English

PHP从具有不同数组数的对象数组中获取特定属性

[英]PHP Get a specific property from an array of objects with different array count

I am in a confusing situation right now. 我现在处于混乱状态。

So, I have an array of objects 所以,我有一个对象数组

array:3 [▼
  0 => array:5 [▶]
  1 => array:2 [▶]
  2 => array:10 [▶]
]

Each array items contains another array which will have objects 每个数组项包含另一个将包含对象的数组

array:3 [▼
  0 => array:5 [▼
    0 => {#215 ▼
      +"DefaultTimeLength": 40
      +"ProgramID": 4
      +"NumDeducted": 1
      +"ID": 245
      +"Name": "30-Swedish-Massage"
    }
    1 => {#216 ▼
      +"DefaultTimeLength": 70
      +"ProgramID": 4
      +"NumDeducted": 1
      +"ID": 246
      +"Name": "60-Swedish-Massage"
    }
    2 => {#217 ▶}
    3 => {#218 ▶}
    4 => {#219 ▶}
  ]
  1 => array:2 [▶]
  2 => array:10 [▶]
]

What I want to achieve is, I want to get the 'ID' and 'Name' as an array for every array of objects from this array. 我想要实现的是,我想从该数组的每个对象数组中获取“ ID”和“名称”作为数组。 Since, every array inside the main array have different counts, I cannot use a FOR loop, to get the required data. 因为主数组中的每个数组都有不同的计数,所以我不能使用FOR循环来获取所需的数据。 Any ideas? 有任何想法吗?

use nested foreach loop eg: 使用嵌套的foreach循环,例如:

foreach($main as $m){
   foreach($m as $item){
     echo $item->ID ." ".$item->Name;
   }
}

use 2 foreach loop inside eachother 在彼此之间使用2 foreach循环

    foreach ($array as $item) {
         foreach ($item as $sub) {
            echo $sub['ID'] . " " . $sub['Name'] . "<br>";
         }
     }

your full code will be something like this 您的完整代码将是这样的

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

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