如何foreach数组的对象,实际上是另一个对象的字段


How foreach array of object that actually field of another object?

我有这样的对象数据结构:

"site":"http://mercurygold.com.ua/",
"shops":[
      { 
         "id":"1",
         "shopLogo":"mercuryGoldShop1",
         "address":"test test test"
      },
      { 
         "id":"2",
         "shopLogo":"mercuryGoldShop2",
         "address":"text text text"
      }
   ]

如何在不按名称寻址字段的情况下对所有"商店"对象进行foreach?

您可以使用2个foreach循环访问它。假设"商店"在变量$var中,您可以这样访问它:

foreach($var['shops'] as $shop)
{
   foreach($shop as $key=>$val)
   {
      echo $key . ": " . $val . "'n";
   }
}

注意:如果变量是JSON,则必须首先执行$var = json_decode($var);

我很确定这是一种JSON格式,要获得元素shops,您需要这样做:

<?php
  $var = '
  {
      "site":"http://mercurygold.com.ua/",
      "shops":[
      { 
         "id":"1",
         "shopLogo":"mercuryGoldShop1",
         "address":"test test test"
      },
      { 
         "id":"2",
         "shopLogo":"mercuryGoldShop2",
         "address":"text text text"
      }
   ]
 }';
 $var = json_decode($var); 
 foreach($var->shops as $shop)
 {
     foreach($shop as $key=>$val)
     {
        echo $key . ": " . $val . "'n";  
     }
     echo '<br>';
 }

输出:

id: 1 shopLogo: mercuryGoldShop1 address: test test test
id: 2 shopLogo: mercuryGoldShop2 address: text text text