使用foreach获取3乘3的数组元素

时间:2014-02-02 05:42:37

标签: php

我有一个数组,其中包含通过拆分字符串获取的数据。

麦克,20%,男性,安,28,女性,卡盘,45,阳

$people = explode(',', $result);

如何使用foreach将数组3中的数据3分配到3个不同的变量中?

    Mike 20 male

    and then 

    Ann 28 female

    then 

    chuck 45 male

3 个答案:

答案 0 :(得分:5)

foreach(array_chunk(explode(',', $result), 3) as $row) {
  list($name, $age, $gender) = $row;
}

实际上,甚至更好:

foreach(array_chunk(explode(',', $result), 3) as list($name, $age, $gender)) {

}

答案 1 :(得分:2)

这是一个选项

$result = 'Mike,20,male,Ann,28,female,chuck,45,male';
$people = explode( ',', $result );
$final_result = array();
$i = 0;
$n = 0;
foreach ( $people as $keys => $values ) {
    $final_result[$n][] = $values;
    $i++;
    if ( $i%3 === 0 ) {
        $n++;
    }
}

答案 2 :(得分:0)

$data = array("mike","20","male","Milaf","21","male","Ava","22","female");
$names = array();
for($i=0 ; $i<9 ; $i+=3){
$names[] = $data[$i];
}
foreach($names as $name){
echo $name.'<br>';
}


$ages = array();
for($i=1 ; $i<10 ; $i+=3){
$ages[] = $data[$i];
}
foreach($ages as $age){
echo $age.'<br>';
}

$genders = array();
for($i=2 ; $i<10 ; $i+=3){
$genders[] = $data[$i];
}
foreach($genders as $gender){
echo $gender.'<br>';
 }

$fullName = array();


for($i = 0 ; $i<3 ; $i++){
$fullName[] =$names[$i].$ages[$i].$genders[$i];
echo $fullName[$i]."<br>";
}