这里需要什么样的循环

时间:2014-03-07 14:13:57

标签: php loops multidimensional-array

我有一系列车轮数据(尺寸,应用(整体半径)和价格)。 我想循环它填补一个表。不幸的是,我无法弄清楚这里需要什么样的循环。我现在已经尝试了几天:(

$wheel = array (
'DIMENSIONS_EACH' => array (
    '7,0 x 16',
    '7,5 x 17',
    '8,0 x 17',
    '8,0 x 18',
    '8,5 x 17'
),
'APPS_EACH'=> array (
    '5 x 120',
    '5 x 120',
    '5 x 120',
    '5 x 120',
    '5 x 120',
    '5 x 120'
),
'PRICE_EACH'=> array (
    '96',
    '117',
    '118',
    '155',
    '156',
    '204'
    )
);

对于第一行,结果应该是这样的,所以儿子:

Dimension | Application | Price
7,0 x 16     5 x 120     96,- €
7,5 x 17     5 x 120    117,- €
....

发布错误的解决方案是没有意义的,因为我有几十个没有作品。请给我一个提示,这里需要什么样的循环。非常感谢。

4 个答案:

答案 0 :(得分:1)

您将需要两个嵌套的foreach循环。

foreach ($wheel as $type => $items) {
    foreach ($items as $item) {
        // Perform your insert
    }
}

答案 1 :(得分:0)

如果每个条目的顺序正确,并且每个数组的长度相同。我们首先获得计数并通过索引循环。

$count = count($wheel['DIMENSIONS_EACH']));

之后,您可以执行for循环来访问三个数组中的每个索引。

$count = count($wheel['DIMENSIONS_EACH']);
$table = array();
for ($i = 0; $i < $count; $i++) {
    $table[] = array(
        $wheel['DIMENSIONS_EACH'][$i],
        $wheel['APPS_EACH'][$i],
        $wheel['PRICE_EACH'][$i]
    );
}

echo '<pre>';
print_r($table);

http://ideone.com/QfgyaI

答案 2 :(得分:0)

我会这样解决(未经测试的代码 - &gt;无保修):

$content = <<< heredoc
<html>
    <head><title>UNTESTED</title></head>
    <body>
      <table>
        <thead>
          <tr>
            <th>Dimension</th>
            <th>Application</th>
            <th>Price</th>
          </tr>
        </thead>
       <tbody>

heredoc;

$count = count($wheel);

for ($i = 0; $i < $count; $i++) {
  $dimension = $wheel["DIMENSIONS_EACH"][$i];
  $apps = $wheel["APPS_EACH"][$i];
  $price = $wheel["PRICE_EACH"][$i];

  $content .= <<< heredoc
  <tr>
    <td>$dimension</td>
    <td>$apps</td>
    <td>$price</td>
  </tr>
heredoc;
}

$content.= <<< heredoc

    </tbody>
  </table>
</html>
heredoc;

echo $content;

答案 3 :(得分:0)

尝试

foreach($wheel['DIMENSIONS_EACH'] as $key=>$value ){

  echo $value. "-".$wheel['APPS_EACH'][$key]."-".$wheel['PRICE_EACH'][$key]."<br>";

}

请参阅演示here