分解平面数组中的每个字符串

问题描述 投票:0回答:3

我有一个来自后期操作的数组

$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 个。不太确定我做错了什么。任何帮助表示赞赏。谢谢你

php arrays string multidimensional-array explode
3个回答
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
投票

试试这个

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);
© www.soinside.com 2019 - 2024. All rights reserved.