我写了一个php代码,我用这个代码编写一个这样的数组:
Array
(
[0] => Men's 100 metres
[1] => Tom Burke
[2] => Fritz Hofmann
[3] => Array
(
[0] => Alajos Szokoly
[1] => Frank Lane
)
)
我知道这个数组元素的值总是在同一个位置:
Position 0 --> the event sport
Position 1 --> who won gold medal
Position 2 --> who won silver medal
Position 3 --> who won bronze medal
2名或更多运动员有可能获得金牌,或者2名或更多运动员可以赢得银牌。以上只是一个例子。
所以我想得到这个结果:
$gender = Men
$event = 100 metres
$athlete = Tom Burke
$medal = Gold
Second loop:
$gender = Men
$event = 100 metres
$athlete = Fritz Hofmann
$medal = Silver
Third loop:
first internal loop:
$gender = Men
$event = 100 metres
$athlete = Alajos Szokoly
$medal = Bronze
second internal loop:
$gender = Men
$event = 100 metres
$athlete = Frank Lane
$medal = Bronze
我该怎么办?
答案 0 :(得分:0)
在遍历时,您只需检查值是否为数组。如果它,那就让它遍历吧。
$a = array(
"Men's 100 metres",
"Tom Burke",
"Fritz Hofmann",
array("Alajos Szokoly", "Frank Lane"));
foreach( $a as $key => $value ){
if(is_array($value)){
foreach($value as $k=>$v){
echo $k."\t=>\t".$v."\n";
}
} else {
echo $key."\t=>\t".$value."\n";
}
}
答案 1 :(得分:0)
我建议将数据结构转换为您的需求,如下所示:
// Sample data:
$events = [
["Men's 100 metres", "Tom Burke", "Fritz Hofmann", ["Alajos Szokoly", "Frank Lane"]],
["Men's 200 metres", ["John", "Mark"], "James", "Patrick"]
];
// Conversion:
$medals = ["gold", "silver", "bronze"];
foreach ($events as $row) {
$gender = "";
$event = array_shift($row);
if (strpos($event, "'s ") > 0) {
list($gender, $event) = explode("'s ", $event);
}
foreach ($row as $i => $athletes) {
if (!is_array($athletes)) $athletes = [$athletes];
foreach($athletes as $athlete) {
$result[] = [
"gender" => $gender,
"event" => $event,
"athlete" => $athlete,
"medal" => $medals[$i]
];
}
}
}
之后你将拥有$result
数组,如下所示:
[
[
'gender' => 'Men',
'event' => '100 metres',
'athlete' => 'Tom Burke',
'medal' => 'gold',
],
[
'gender' => 'Men',
'event' => '100 metres',
'athlete' => 'Fritz Hofmann',
'medal' => 'silver',
],
[
'gender' => 'Men',
'event' => '100 metres',
'athlete' => 'Alajos Szokoly',
'medal' => 'bronze',
],
[
'gender' => 'Men',
'event' => '100 metres',
'athlete' => 'Frank Lane',
'medal' => 'bronze',
],
[
'gender' => 'Men',
'event' => '200 metres',
'athlete' => 'John',
'medal' => 'gold',
],
[
'gender' => 'Men',
'event' => '200 metres',
'athlete' => 'Mark',
'medal' => 'gold',
],
[
'gender' => 'Men',
'event' => '200 metres',
'athlete' => 'James',
'medal' => 'silver',
],
[
'gender' => 'Men',
'event' => '200 metres',
'athlete' => 'Patrick',
'medal' => 'bronze',
],
]
这很容易输出。