在数组中循环遍历数组并将值输出到PHP

时间:2015-05-04 17:30:39

标签: php arrays loops foreach nested-loops

我有一个阵列......

array (size=2)
  'prd' => 
    array (size=8)
      0 => string '1' (length=1)
      1 => string '2' (length=1)
      2 => string '3' (length=1)
      3 => string '4' (length=1)
      4 => string '5' (length=1)
      5 => string '6' (length=1)
      6 => string '7' (length=1)
      7 => string '8' (length=1)
  'price' => 
    array (size=8)
      0 => string 'a' (length=1)
      1 => string 'b' (length=1)
      2 => string 'c' (length=1)
      3 => string 'd' (length=1)
      4 => string 'e' (length=1)
      5 => string 'f' (length=1)
      6 => string 'g' (length=1)
      7 => string 'h' (length=1)

我希望输出看起来像这样......

1成本a,2成本b,3成本c,4成本d,5成本e,6成本f,7成本g,8成本h

到目前为止,我已尝试过以下内容......

foreach ($array as $values) {

    foreach ($values as $val ) {
        echo $val;
    }

}

这给了我按顺序排列的数组......

12345678abcdefgh

如何输出

1a2b3c4d5e6f7g8h

我可以处理格式,只是在处理订单。

2 个答案:

答案 0 :(得分:4)

有几种方法,这里有两种方式。

使用循环数组的键访问另一个:

foreach($array['prd'] as $key => $val) {
    echo $val . $array['price'][$key];
}

组合成键和值:

$array = array_combine($array['prd'], $array['price']);

foreach($array as $key => $val) {
    echo $key . $val;
}

答案 1 :(得分:3)

试试这个

$data = array (
  'prd' => array (
      0 => '1', 
      1 => '2', 
      2 => '3', 
      3 => '4', 
      4 => '5', 
      5 => '6', 
      6 => '7', 
      7 => '8', 
   ),
  'price' =>  array (
      0 => 'a', 
      1 => 'b', 
      2 => 'c', 
      3 => 'd', 
      4 => 'e', 
      5 => 'f', 
      6 => 'g', 
      7 => 'h', 
   )
);

for ($x = 0; $x< count($data['prd']); $x++) {
  echo $data['prd'][$x] . " costs " . $data['price'][$x] . PHP_EOL;
}