简体   繁体   English

使用stdClass对象遍历php数组

[英]Loop through php array with stdClass Object

How do I loop through this array and get all the term_id's? 如何遍历此数组并获取所有term_id?

Array (
    [0] => stdClass Object (
        [term_id] => 43
    )
    [1] => stdClass Object (
        [term_id] => 25
    )
)
$ob1 = new stdClass();
$ob1->term_id = 43;

$ob2 = new stdClass();
$ob2->term_id = 25;

$scope = array($ob1,$ob2);

foreach($scope as $o){
  echo $o->term_id.'<br/>';
}

// Out
// 43
// 25

Each element of your array is an regular object, so yo can access it just by for (if elements of array are in order and keys are integers) or foreach (in examples $a is given array): 数组中的每个元素都是一个常规对象,因此您可以按for (如果array的元素是有序的并且键是整数)或foreach (在示例中$a给出了array)来访问它:

For: 对于:

$count = sizeof($a);
for ($i = $count; $i--;)
{
    echo $a[$i]->term_id;
}

Foreach: Foreach:

foreach ($a as $item)
{
    echo $item->term_id;
}

If you want to add all ids to another array, you just need to write following code (in example for foreach): 如果要将所有id添加到另一个数组,则只需要编写以下代码(例如foreach):

$ids = array();
foreach ($a as $item)
{
    $ids[] = $item->term_id;
}

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

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