简体   繁体   中英

Loop through array in arrays and output values together PHP

I have an array...

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)

I want the output to look like this...

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

so far I have tried the following...

foreach ($array as $values) {

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

}

this gives me the arrays in order...

12345678abcdefgh

How do I get it to output

1a2b3c4d5e6f7g8h

I can handle the format, just struggling with the order.

There are several ways, here are two.

Use the key of the looped array to access the other:

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

Combine into keys and values:

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

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

Try this

$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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM