具有2个以上对象的foreach循环

时间:2015-01-09 05:44:59

标签: php foreach

示例:

$get = file_get_contents("example-page-goes-here");

preg_match_all('/yadayada=\"(.*?)\" yadayada=\"(.*?)\" yadayada=\"yadayada\" yadayada=\"(.*?)\">/', $get, $title);

foreach ($title[1] as $link, $title[2] as $img, $title[3] as $title)
{
echo $link."<br>";
echo $img."<br>";
echo $title."<br>";
}

这可能吗?

2 个答案:

答案 0 :(得分:0)

不,这是不可能的。 请查看documentation

你可以这样做:

<?php

foreach ($title as $index => $item) {
  if ($index == 1) {
    // $item is link now.
  }
}

此外,我建议您查看switch文档页面。

答案 1 :(得分:0)

只需扩展@HankyPanky的答案,您可以使用max()count()找到最长的数组长度,然后执行到该长度的循环。

例如

获取最大数量

$count = array();
for($i = 1; $i <= 3; $i++){
  $count[$i] = count($title[$i]);
}
$maxCount = max($count);

然后按需要迭代并处理,如此

for($x = 0; $x <= $maxCount; $x++){
  $link = '';
  $img = '';
  $title = '';

  if(isset($title[1][$x])){
    $link =  $title[1][$x];
  }

  if(isset($title[2][$x])){
    $img =   $title[2][$x];
  }

  if(isset($title[3][$x])){
    $title = $title[3][$x];
  }

  echo $link;
  echo $img;
  echo $title;
}

这不是最有效的方式,你可以修改它,但我认为这种方法是可行的。

相关问题