我有一个数组,我想要打印这个数组,但键值应该在第一次打印一次,然后打印数组值。
array(
array(
'Name'=> 'Trixie',
'Color'=> 'Green',
'Element'=> 'Earth',
'Likes'=> 'Flowers'
),
array(
'Name'=> 'Tinkerbell',
'Element'=> 'Air',
'Likes'=> 'Singning',
'Color'=> 'Blue'
),
array(
'Element'=> 'Water',
'Likes'=> 'Dancing',
'Name'=> 'Blum',
'Color'=> 'Pink'
),
);
期待这个输出:
Name Color Element Likes
Trixie Green Earth Flowers
Tinkerbell Blue Air Singing
Blum Pink Water Dancing
答案 0 :(得分:2)
$x = //the array
//get the keys from the first item in the array and loop
foreach (array_keys($x[0]) as $key) {
//echo each key
echo $key;
}
//loop the array
foreach ($x as $arr) {
//loop each item of the sub array
foreach ($arr as $v) {
//echo item's value
echo $v;
}
}
答案 1 :(得分:1)
试试这样: 现场演示:https://eval.in/90748
$arr = array(
array(
'Name'=> 'Trixie',
'Color'=> 'Green',
'Element'=> 'Earth',
'Likes'=> 'Flowers'
),
array(
'Name'=> 'Tinkerbell',
'Element'=> 'Air',
'Likes'=> 'Singning',
'Color'=> 'Blue'
),
array(
'Element'=> 'Water',
'Likes'=> 'Dancing',
'Name'=> 'Blum',
'Color'=> 'Pink'
),
);
echo "Name Color Element Likes"."<br />";
foreach($arr as $ar){
echo $ar['Name']." ".$ar['Color']." ".$ar['Element']." ".$ar['Likes']."<br />";
}
<强>输出:强>
Name Color Element Likes
Trixie Green Earth Flowers
Tinkerbell Blue Air Singning
Blum Pink Water Dancing
答案 2 :(得分:1)
<?php
$yourarray = array(
array(
'Name'=> 'Trixie',
'Color'=> 'Green',
'Element'=> 'Earth',
'Likes'=> 'Flowers'
),
array(
'Name'=> 'Tinkerbell',
'Element'=> 'Air',
'Likes'=> 'Singning',
'Color'=> 'Blue'
),
array(
'Element'=> 'Water',
'Likes'=> 'Dancing',
'Name'=> 'Blum',
'Color'=> 'Pink'
),
);
echo "<table>";
echo "<tr><td>Name</td><td>Color</td><td>Element</td><td>Likes</td></tr>";
foreach($yourarray as $value){
echo "<tr>";
echo "<td>".$value['Name']."</td><td>".$value['Color']."</td><td>".$value['Element']."</td><td>".$value['Likes']."</td>";
echo "</tr>";
}
echo "</table>";
?>