【问题标题】:Exploding an array of strings分解字符串数组
【发布时间】:2013-03-13 06:11:29
【问题描述】:

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

$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 循环也不起作用,因此将其注释掉,但如果需要,将其作为一个选项保留。

print 函数现在只打印数组中的 1 个。不完全确定我做错了什么。任何帮助表示赞赏。谢谢

【问题讨论】:

  • 在你的循环之后尝试print_r($country);

标签: php arrays string multidimensional-array explode


【解决方案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];

【讨论】:

  • 非常感谢...我还是不明白...因为我确实使用了这条线... $r[] = explode(",", $country_item);为此我收到一个错误:致命错误:第 21 行 C:\wamp\www\clar\test5.php 中的字符串不支持 [] 运算符...但是当我输入您的代码时它起作用了...谢谢再次
【解决方案2】:

试试这个

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

【讨论】:

    【解决方案3】:

    您正在使用循环中的 $r 覆盖您的 $r 主数组 - 这是解决方案 - 始终划分您的变量:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 2011-11-13
      相关资源
      最近更新 更多