【问题标题】:convert explode results to array in key, value将爆炸结果转换为键、值中的数组
【发布时间】:2017-10-04 15:32:44
【问题描述】:

我有类似的数据

list=7251270233&total_amount=28841.28&r_g_amount=1800&cash=1000&credit=500&bank=300&bank_from=abc&bank_to=pqr

使用explode 将其转换为array 并得到类似的结果

0:"list=7251270233"
1:"total_amount=28841.28"
2:"r_g_amount=1800"
3:"cash=1000"
4:"credit=500"
5:"bank=300"
6:"bank_from=abc"
7:"bank_to=pqr"

现在我将其转换为key->value 中的数组,例如:

array("list"=>"7251270233",
"total_amount"=>"28841.28",
"r_g_amount"=>"1800",
"cash"=>"1000",
"credit"=>"500",
"bank"=>"300",
"bank_from"=>"abc",
"bank_to"=>"pqr")

那么如何转换成数组

【问题讨论】:

  • 使用 parse_str() 函数可以轻松地将查询字符串转换为数组。正如我在回答中所做的那样。请检查

标签: php arrays laravel explode


【解决方案1】:

使用parse_str将其转换为数组非常简单

然后像下面这样:

 $query_string = "list=7251270233&total_amount=28841.28&r_g_amount=1800&cash=1000&credit=500&bank=300&bank_from=abc&bank_to=pqr";

 $data_array = parse_str($query_string, $output);

print_r($output);

输出如下:

Array
(
    [list] => 7251270233
    [total_amount] => 28841.28
    [r_g_amount] => 1800
    [cash] => 1000
    [credit] => 500
    [bank] => 300
    [bank_from] => abc
    [bank_to] => pqr
)

【讨论】:

    【解决方案2】:

    检查一下

    <?php
    $string = "list=7251270233&total_amount=28841.28&r_g_amount=1800&cash=1000&credit=500&bank=300&bank_from=abc&bank_to=pqr";
    
    $info = explode("&",$string);
    $result = array();
    foreach ($info as $val) {
        $sub = explode("=",$val);
        $result[$sub[0]] = $sub[1];
    }
    
    echo "<pre>".print_r($result,1)."</pre>";
    ?>
    

    结果:

    Array
    (
        [list] => 7251270233
        [total_amount] => 28841.28
        [r_g_amount] => 1800
        [cash] => 1000
        [credit] => 500
        [bank] => 300
        [bank_from] => abc
        [bank_to] => pqr
    )
    

    【讨论】:

      【解决方案3】:
      <?php 
      $str = 'list=7251270233&total_amount=28841.28&r_g_amount=1800&cash=1000&credit=500&bank=300&bank_from=abc&bank_to=pqr';
      $strarr = explode('&',$str);
      print_r($strarr);
      foreach($strarr as $stra){
          $result[explode('=',$stra)[0]] = explode('=',$stra)[1];
      }
      
      print_r($result);
      

      输出

      Array
      (
          [list] => 7251270233
          [total_amount] => 28841.28
          [r_g_amount] => 1800
          [cash] => 1000
          [credit] => 500
          [bank] => 300
          [bank_from] => abc
          [bank_to] => pqr
      )
      

      https://eval.in/788202

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多