Reputation: 67
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.
Upvotes: 3
Views: 1180
Reputation: 791
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;
}
Upvotes: 3
Reputation: 78994
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;
}
Upvotes: 4