开发者

How to map values from array to use in for loop?

开发者 https://www.devze.com 2023-03-17 02:27 出处:网络
How I can turn this Array ( [0] => feed [1] => entry ) into this: foreach ($data->feed->entry as $item) { // Yep, we made it }

How I can turn this

Array
(
    [0] => feed
    [1] => entry
)

into this:

foreach ($data->feed->entry as $item) { // Yep, we made it }

The first array can have any number of values, so solution needs to be flexible.

EDIT: Dogbert gave me perfect answer, but to make this more clear for f开发者_如何学Pythonuture. What I have is only one array. Based on that I need to get array from object. So my array might look like this also:

[0] => world
[1] => countries
[2] => finland
[3] => helsinki
[4] => people

And then I would need to get:

foreach ($data->world->countries->finland->helsinki->people as $item) {}


function map_property($obj, $array) {
  $ret = $obj;
  foreach($array as $prop) {
    $ret = $ret->$prop;
  }
  return $ret;
}

foreach(map_property($data, array('feed', 'entry')) as $item) { }


If you need key => value in loop do it like this:

foreach ($data->feed->entry as $key=>$item) {
// Yep, we made it
echo 'This is key:'.$key.' this is item: '.$item;
}

you will get result

This is key: 0 this is item: feedThis is key: 1 this is item: entry

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号