2013-03-23 129 views
0

我从一个岗位操作的阵列爆炸字符串数组

$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

尝试'的print_r($国家);'你的循环后,而不是 – Crisp 2013-03-23 11:51:44

回答

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]; 
+0

非常感谢你...我仍然不明白,但...因为我确实使用这条线...... $ r [] = explode(“,”,$ country_item);为此我得到一个错误:致命错误:[]运算符不支持C:\ wamp \ www \ clar \ test5.php中第21行的字符串...但它在我输入代码时起作用...谢谢再次 – 2013-03-23 12:08:07

0

试试这个

for($i=0;$i<count($country);$i++) 
{ 
     $country1[$i] = explode(",", $country[$i]); 
} 
0

要覆盖你的$ R主阵列从环路$ R - 这是解决方案 - 总是将您的增值经销商:

$output = array(); 
foreach($country as $c){ 
    $parts = explode(',',$c); 
    $output[] = $parts; 
} 

print_r($output);