【问题标题】:String as 2 D array字符串作为二维数组
【发布时间】:2014-05-28 17:03:39
【问题描述】:

我正在使用 PHP,我从数据库中获取了一个字符串,其结构类似于: $string = "a:b;c:d;e:f;g:h;"依此类推,其中 a、b、c.. 是变量, a,c 和 e 不能是连续数字,它们可以是 1 到 500 之间的数字。 我需要将此字符串转换为具有以下格式的数组:

$array [a] == ("b");
$array [c] == ("d");
$array [e] == ("f");

等等……

但我不知道如何从字符串中获取两个子字符串(双点分隔,点逗号分隔)并将其放入二维字符串中。

提前谢谢你

【问题讨论】:

    标签: php arrays string variables substring


    【解决方案1】:

    要在没有 foreach 循环的情况下操作结果数组的键和值,可以使用array_reduce

    $string = "a:b;c:d;e:f;g:h;";
    
    $array = array_reduce( array_filter( explode( ';', $string ) ), function( $result, $item ) {
        $tmp = explode( ':', $item );
        $result[$tmp[0]] = $tmp[1];
        return $result;
    });
    

    输出:

    Array (
        [a] => b
        [c] => d
        [e] => f
        [g] => h 
    )
    

    【讨论】:

      【解决方案2】:

      不知道你在问什么,但这可能对你有帮助

      $re = '/(.?):(.?)/'; 
      $str = 'a:b;c:d;e:f;g:h;'; 
      
      preg_match_all($re, $str, $matches);
      
      print_r(array_combine($matches[1],$matches[2]));
      

      输出:

      (
          [a] => b
          [c] => d
          [e] => f
          [g] => h
      )
      

      【讨论】:

        【解决方案3】:

        使用explode(),这将是split a string into an array based on the specified delimiter

        $string = "a:b;c:d;e:f;g:h;";
        $temparray = explode(';', $string);
        //$temparray now looks like ['a:b', 'c:d', 'e:f']
        //use explode() again in a loop to split up each index
        
        $finalarray = array();
        foreach($temparray as $arr){
          $splitarr = explode(':', $arr);
          //$splitarr will look something like ['a', 'b']
          //use those values to set the indexes in your final array
          $finalarray[$splitarr[0]] = $splitarr[1];
        }
        $finalarray=array_filter($finalarray);//to remove null values
        //print_r($finalarray);
        

        注意:仅供参考,由于字符串中的尾随 ;,您最终可能会在数组末尾有一个额外的空索引,因此需要调用 array_filter(),感谢 @FerozAkbar

        【讨论】:

          猜你喜欢
          • 2018-12-08
          • 2019-01-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-18
          • 2016-05-06
          • 2013-03-28
          • 1970-01-01
          相关资源
          最近更新 更多