【问题标题】:Change Array values to json format in php在php中将数组值更改为json格式
【发布时间】:2014-05-03 04:32:20
【问题描述】:

我有一个这样的数组

Array
            (
                [0] => [{"qty":"4023","discount":"-288.84000194072723"}]
                [1] => [{"qty":"48","discount":"-1"}]
                [2] => [{"qty":"305","discount":"0"}]
            )

如何将这些数组转换为我的格式

 [{"name":"qty","data":[4023,48,305]},{"name":"discount","data":[-288.84,-1,0]}] 

如何解决这个问题?

【问题讨论】:

  • 希望我们为您搜索一下吗?
  • 我为您发布了我的解决方案,它不起作用吗?
  • 谢谢贾里!!!!!!!!!它的工作正常........

标签: php arrays json codeigniter


【解决方案1】:

这是完整的解决方案(使用json_encodejson_decode):

$array = array(
  '[{"qty":"4023","discount":"-288.84000194072723"}]',
  '[{"qty":"48","discount":"-1"}]',
  '[{"qty":"305","discount":"0"}]'
);

$new = array(
  (object) array("name" => "qty", "data" => array()),
  (object) array("name" => "discount", "data" => array())
);

foreach($array as $key => $value){
  $object = json_decode($value)[0];

  $new[0]->data[] = $object->qty ;
  $new[1]->data[] = $object->discount ;
}


$desired_result = json_encode($new);
var_dump($desired_result);

用于测试的沙盒:Here

【讨论】:

    【解决方案2】:

    看看json_encode函数。

    来自 PHP.net 的示例:

    <?php
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
    
    echo json_encode($arr);
    ?> 
    

    输出:

    {"a":1,"b":2,"c":3,"d":4,"e":5}
    

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 2015-05-29
      • 2017-09-29
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多