duanguai2781 2016-08-04 14:54
浏览 53
已采纳

PHP - 使用文本字符串中的键创建数组

I have simple text string, it is looking like that:

30143*1,30144*2,30145*3,30146*5,30147*5

And i have to transform this text string to array with this structure:

Array ( [0] => Array ( [product] => 30143 [qty] => 1 ) [1] => Array ( [product] => 30144 [qty] => 2 ) [2] => Array ( [product] => 30145 [qty] => 3 ) [3] => Array ( [product] => 30146 [qty] => 4 ) [4] => Array ( [product] => 30147 [qty] => 5 ) )

Is it even possible and if so how?

I found this:

$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);

But this is only creating the array with no keys and wtih example there is no way to get the qty key with *.

Thanks in advance!

  • 写回答

4条回答 默认 最新

  • douhaodang0403 2016-08-04 14:59
    关注

    Here you go. You need to iterate through all the 30143*1 items. array_map do this job for you.

    function getPieces($val) {
        $pieces  = explode('*', $val);
        return ['product' => $pieces[0], 'qty' => $pieces[1]];
    }
    
    $str = '30143*1,30144*2,30145*3,30146*5,30147*5';
    $result = array_map('getPieces', explode(',', $str));
    
    var_dump($result);
    

    OUTPUT:

    array (size=5)
      0 => 
        array (size=2)
          'product' => string '30143' (length=5)
          'qty' => string '1' (length=1)
      1 => 
        array (size=2)
          'product' => string '30144' (length=5)
          'qty' => string '2' (length=1)
      2 => 
        array (size=2)
          'product' => string '30145' (length=5)
          'qty' => string '3' (length=1)
      3 => 
        array (size=2)
          'product' => string '30146' (length=5)
          'qty' => string '5' (length=1)
      4 => 
        array (size=2)
          'product' => string '30147' (length=5)
          'qty' => string '5' (length=1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?