I am trying to create a foreach that will go through some variables within an object.

At the moment it is just

class jabroni
{
  var $name = "The Rock";
  var $phrases = array ("The rock says", "Im gonna put the smackdown on you", "Bring it on jabroni");
  var $moves = array ("Clothes line", "Pile driver", "Reverse flip");
}

I tried doing this:

$jabroni = new jabroni()
foreach ($jabroni as $value)
{
  echo $value->phrases;
  echo $value->moves;
}

However nothing gets printed.

Any ideas if what I am trying to achieve is possible, I have that gut feeling that its not and that I will have to just do individual foreach statements for each object member variable that is an area?

Thanks for your time!

有帮助吗?

解决方案

You are doing wrong the loop.. You have one object, not an array of objects. so the correct way should be..

$jabroni = new jabroni();
foreach ($jabroni->phrases as $value)
{
    echo $value;
}
foreach ($jabroni->moves as $value)
{
    echo $value;
}

其他提示

foreach ($jabroni->phrases as $value) {
    echo $value;
}

foreach ($jabroni->moves as $value) {
    echo $value;
}

You can do it in nested foreach loops. This will be easy instead of going for two for loops seperatley

foreach ($jabroni as $keys => $values)
{
    if ($keys == 'phrases' || $keys == 'moves') {
           foreach ($values as $value) {
             echo $value;
           }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top