PHP Foreach 数组和对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13707836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:55:32  来源:igfitidea点击:

PHP Foreach Arrays and objects

phparraysstdclass

提问by AttikAttak

I have an array of objects. A print_routput looks like this:

我有一个对象数组。一个print_r输出如下:

Array
(
    [0] => stdClass Object
        (
            [sm_id] => 1
            [c_id] => 1
        )
    [1] => stdClass Object
        (
            [sm_id] => 1
            [c_id] => 2

        )
)

I am really struggling to find a way to loop though the results and access the object elements. If anyone could give me any pointers i would be extremely grateful.

我真的很难找到一种方法来循环遍历结果并访问对象元素。如果有人能给我任何指示,我将不胜感激。

Thanks in advance

提前致谢

回答by GBD

Use

//$arr should be array as you mentioned as below
foreach($arr as $key=>$value){
  echo $value->sm_id;
}

OR

或者

//$arr should be array as you mentioned as below
foreach($arr as $value){
  echo $value->sm_id;
}

回答by Sampson

Looping over arrays and objects is a pretty common task, and it's good that you're wanting to learn how to do it. Generally speaking you can do a foreachloopwhich cycles over each member, assigning it a new temporary name, and then lets you handle that particular member via that name:

循环遍历数组和对象是一项非常常见的任务,如果您想学习如何执行此操作是件好事。一般来说,你可以做一个foreach循环,其循环在每个成员,分配给它一个新的临时名称,然后让你通过这个名字办理特定成员:

foreach ($arr as $item) {
    echo $item->sm_id;
}

In this example each of our values in the $arrwill be accessed in order as $item. So we can print our values directly off of that. We could also include the index if we wanted:

在这个例子中,我们在 中的每个值都$arr将按顺序访问为$item。所以我们可以直接打印出我们的值。如果需要,我们还可以包含索引:

foreach ($arr as $index => $item) {
    echo "Item at index {$index} has sm_id value {$item->sm_id}";
}

回答by Ronny Sherer

Recursive traverse object or array with array or objects elements:

递归遍历具有数组或对象元素的对象或数组:

function traverse(&$objOrArray)
{
    foreach ($objOrArray as $key => &$value)
    {
        if (is_array($value) || is_object($value))
        {
            traverse($value);
        }
        else
        {
            // DO SOMETHING
        }
    }
}

回答by imkingdavid

Assuming your sm_idand c_idproperties are public, you can access them by using a foreachon the array:

假设您的sm_idc_id属性是公开的,您可以通过foreach在数组上使用 a 来访问它们:

$array = array(/* objects in an array here */);
foreach ($array as $obj) {
    echo $obj->sm_id . '<br />' . $obj->c_id . '<br />';
}