如何拆分字符串并构建一个关联数组php?

问题描述 投票:-1回答:1

如何在PHP中拆分字符串?例如,如果我有像这样的字符串

Array([0] => "1=>10,2=>9,3=>7,1=>9,2=>8,3=>7");

我怎样才能得到

Array([0] => 1=>10,2=>9,3=>7 [1] => 1=>9,2=>8,3=>7);

后来我想构建一个关联数组,例如,

$ratings = array(6533 => ['Build Quality' => [1=>10,2=>9,3=>7], 
                         'Versatility' => [1=>9,2=>8,3=>7], 
                         'value' => [1=>9.5,2=>7,3=>6]]); 

//takes the current post id and returns an product ratings array                  
function get_ratings($current_post_id){

     $product_post = get_post($current_post_id);
     preg_match_all("/\[v360_product_table\s.*?\]/", $product_post>post_content, $product_elements);

     $product_elements = $product_elements[0][0];
     preg_match_all('/"([^"]+)"/', $product_elements, $parameters);
     $product_params = $parameters[0][0];
     $rating_params = preg_split('","', $product_params);
     $rating_factors = str_replace('"', '', $rating_params);
     $b = print_r($rating_factors);
    /* output: Array ( [0] => Build Quality [1] => Versatality [2] => Adoptability) */

     $product_rank = $parameters[0][1]; 
     /* output: Array ( [0] => 1=>10,2=>9,3=>7,1=>9,2=>8,3=>7 )  */ 
     $rank_split = preg_split('"**have to split it here**"', $product_rank);
     $rank_values = str_replace('"', '', $rank_split);

     $assoc_array = array_combine($rating_factors, $rank_values);
     /* needs to construct an array like '$ratings'  */
     $ratings = array(6533 => ['Build Quality' => [1 => 10, 2 => 8, 3 => 7], 
     'Versatility' => [1 => 9, 2 => 9, 3 => 8], 'Value' => [1 => 10, 2 => 8,3 => 8]]);
     return $ratings[$current_post_id];
        }
php wordpress split
1个回答
0
投票

从你的例子中,我猜你想用逗号分隔字符串后跟数字1.要做到这一点,你可以使用preg_split()带有正向前瞻:

$string = "1=>10,2=>9,3=>7,1=>9,2=>8,3=>7";
$split = preg_split('/,(?=1\b)/', $string);
var_dump($split);

得到:

array(2) {
  [0]=>
  string(15) "1=>10,2=>9,3=>7"
  [1]=>
  string(14) "1=>9,2=>8,3=>7"
}

此函数将整个字符串解析为嵌套数组:

function split_string($string)
{
    $split = array();
    foreach (preg_split('/,(?=1\b)/', $string) as $row => $part1) {
        foreach (explode(',', $part1) as $part2) {
            list($key, $value) = explode('=>', $part2, 2);
            $split[$row][$key] = $value;
        }
    }
    return $split;
}

测试如下(在php 5.6中):

$string = "1=>10,2=>9,3=>7,1=>9,2=>8,3=>7";
$split = split_string($string);
var_dump($split);

给出这个输出:

array(2) {
  [0]=>
  array(3) {
    [1]=>
    string(2) "10"
    [2]=>
    string(1) "9"
    [3]=>
    string(1) "7"
  }
  [1]=>
  array(3) {
    [1]=>
    string(1) "9"
    [2]=>
    string(1) "8"
    [3]=>
    string(1) "7"
  }
}

然后,您可以使用array_combine()来合并名称:

$string = "1=>10,2=>9,3=>7,1=>9,2=>8,3=>7";
$split = split_string($string);
var_dump(array_combine(array('Build Quality', 'Versatility'), $split));
© www.soinside.com 2019 - 2024. All rights reserved.