我有一个来自后期操作的数组
$country = $_POST['country']; //The number of countries differ according to the user selection
$c = count($country);
输出:`
Array ( [0] => England,69,93 [1] => Australia,79,84 [2] => Greece,89,73 [3] => Germany,59,73 )`
我必须将其分解为多维数组,如:
> Array ( [0] => Array ( [0] => England [1] => 69 [2] => 93)
> [1] => Array ( [0] => Australia [1] => 79 [2] => 84)
> [2] => Array ( [0] => Greece [1] => 89 [2] => 73)
> [3] => Array ( [0] => Germany [1] => 59 [2] => 73))
我如何在PHP中执行此操作
我试过
$r = array();
foreach($country as &$r){
$r = explode(",", $r);
//for($i = 0; $i < count($country); $i++){
//for($j = 0; $j < count($r); $j++){
//$array[$i][$j] = $r;
//}
//}
}
echo '<br>';
print_r($r);
for循环也不起作用,因此对其进行了评论,但如果需要则将其作为一个选项。
打印功能现在只打印1个数组。不完全确定我做错了什么。任何帮助表示赞赏。谢谢
答案 0 :(得分:1)
你快到了那里:
$r = array();
foreach($country as $country_item){
$r[] = explode(",", $country_item);
}
echo '<br>';
print_r($r);
上述情况应该有效。
对您来说可能更好(如果您的国家/地区在每个阵列中都是唯一的):
$r = array();
foreach($country as $country_item){
$temp_array = explode(",", $country_item);
$r[$temp_array[0]] = array($temp_array[1], $temp_array[2]);
}
echo '<br>';
print_r($r);
这将为您提供如下输出:
> Array ( [England] => Array ( [0] => 69 [1] => 93)
> [Australia] => Array ( [0] => 79 [1] => 84)
> [Greece] => Array ( [0] => 89 [1] => 73)
> [Germany] => Array ( [0] => 59 [1] => 73))
因此,这意味着您可以访问以下国家/地区的数据:
$r[$country_name];
答案 1 :(得分:0)
试试这个
for($i=0;$i<count($country);$i++)
{
$country1[$i] = explode(",", $country[$i]);
}
答案 2 :(得分:0)
你用循环中的$ r覆盖你的$ r主数组 - 这是解决方案 - 总是划分你的变量:
$output = array();
foreach($country as $c){
$parts = explode(',',$c);
$output[] = $parts;
}
print_r($output);