如何 foreach 遍历作为数组的对象成员变量的一部分?

发布于 2024-12-29 05:51:46 字数 557 浏览 4 评论 0原文

我正在尝试创建一个 foreach 来遍历对象内的一些变量。

目前

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");
}

我只是尝试这样做:

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

但是没有打印任何内容。

如果我想要实现的目标是可能的,我有什么想法,我有一种直觉,它不是,我必须为每个作为区域的对象成员变量执行单独的 foreach 语句?

感谢您抽出时间!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

轻拂→两袖风尘 2025-01-05 05:51:46

你做错了循环。你有一个对象,而不是一组对象。所以正确的方法应该是..

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

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;
}
画骨成沙 2025-01-05 05:51:46
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;
}
迷爱 2025-01-05 05:51:46

您可以在嵌套的 foreach 循环中执行此操作。这将很容易,而不是分别进行两个 for 循环

foreach ($jabroni as $keys => $values)
{
    if ($keys == 'phrases' || $keys == 'moves') {
           foreach ($values 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;
           }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文