drduh44480 2011-07-13 05:04
浏览 33
已采纳

PHP foreach数组

I had to make some changes to my app to work with a relationship change in my db.

Originally I had whats below for a 1::0-1 relationship

if ($model->address->AddressLine1) echo $model->address->AddressLine1.'<br />';
if ($model->address->AddressLine2) echo $model->address->AddressLine2.'<br />';
if ($model->address->city->Name) echo $model->address->city->Name;
if ($model->address->city->regionCode->RegionCode) echo ', '.$model->address->city->regionCode->RegionCode;

but had to change it to work with a 1::0-n relationship

foreach ($model->address as $al1)
foreach ($model->address as $al2)
foreach ($model->address as $al2)
foreach ($model->address as $city)
foreach ($model->address as $region) {
    echo $al1->AddressLine1.' '.$al2->AddressLine2.'<br/>'.$city->city->Name.' '.$city->city->regionCode->RegionCode;
}

I want to retain the functionality of the if in my original code. With the original code I was able to use

', '.

in

if ($model->address->city->regionCode->RegionCode) echo ', '. $model->address->city->regionCode->RegionCode;

to only add a comma after City only when a Region is present in the db.

So how can I get that back and utilize if within my array?

  • 写回答

1条回答 默认 最新

  • dongzouqie4220 2011-07-13 05:07
    关注

    You only need one foreach loop — you're just iterating through a single array.

    You can stick the conditionals into the foreach loop, updating the variable name. This assumes that $model->address is an array. On each iteration $address will be set to a subsequent element of that array.

    foreach ( $model->address as $address ) {
        if ($address->AddressLine1) echo $address->AddressLine1.'<br />';
        if ($address->AddressLine2) echo $address->AddressLine2.'<br />';
        if ($address->city->Name) echo $address->city->Name;
        if ($address->city->regionCode->RegionCode) echo ', '.$address->city->regionCode->RegionCode;
    }
    

    For more information:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类