doubingjian2006
2018-03-13 05:40
浏览 38
已采纳

如何将逗号分隔值与关联数组分开?

I have an array like

Array
(
    [0] => 2,2-0-tc
    [1] => 2-0
    [2] => 2-0-tc
    [3] => 3,3-0-sc-v6
    [4] => 3-0-sc-v6
    [5] => 3-0sc-v6
    [6] => 5-0-sc-v8
)

and I want to extract the comma separated value from array and then create new array like

Array
(
    [2] => 2,2-0-tc
    [2-0-tc] => 2,2-0-tc
    [2-0] => 2-0
    [3] => 3,3-0-sc-v6
    [3-0-sc-v6] => 3,3-0-sc-v6
    [3-0sc-v6] => 3-0sc-v6
    [5-0-sc-v8] => 5-0-sc-v8
)

thanks in addvance

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doutangshuan6473 2018-03-13 06:08
    已采纳

    Explode and iterate each comma-delimited value and prevent overwriting with an isset condition.

    Code: demo: https://3v4l.org/9ArV7

    $array = [
        "2,2-0-tc",
        "2-0",
        "2-0-tc",
        "3,3-0-sc-v6",
        "3-0-sc-v6",
        "3-0sc-v6",
        "5-0-sc-v8"
    ];
    
    foreach ($array as $item) {
        $values = explode(",", $item);
        foreach ($values as $value) {
            if (!isset($result[$value])) {
                 $result[$value] = $item;
            }
        }
    }
    var_export($result);
    

    Output:

    array (
      2 => '2,2-0-tc',
      '2-0-tc' => '2,2-0-tc',
      '2-0' => '2-0',
      3 => '3,3-0-sc-v6',
      '3-0-sc-v6' => '3,3-0-sc-v6',
      '3-0sc-v6' => '3-0sc-v6',
      '5-0-sc-v8' => '5-0-sc-v8',
    )
    
    已采纳该答案
    打赏 评论
  • douhao7889 2018-03-13 06:05

    explode the comma separated values and assign it to new array.

    $arr = array
    (
        0 => '2,2-0-tc',
        1 => '2-0',
        2 => '2-0-tc',
        3 => '3,3-0-sc-v6',
        4 => '3-0-sc-v6',
        5 => '3-0sc-v6',
        6 => '5-0-sc-v8'
    );
    
    $newArr = [];
    foreach($arr as $key=>$val){ 
        $temp = explode (',', $val);
        foreach($temp as $new){
            $newArr[$new] = $val;
        }
    }
    print_r($newArr);
    

    Demo

    打赏 评论

相关推荐 更多相似问题