【问题标题】:how to convert array to ArrayObject with php from json file如何使用 php 从 json 文件将数组转换为 ArrayObject
【发布时间】:2021-12-05 07:20:36
【问题描述】:

我有来自外部 json 文件的数组中的数据。数据如下所示

[
{"serial": 991, "name": "hello"},
{"serial": 993, "name": "world"},
{"serial": 994, "name": "island"}
]

我怎样才能把上面的数据变成下面的例子

array("type"=>"fruit", "price"=>3.50)

我的案例实际上需要使用 multisort 对 json 文件进行排序,每个教程都使用示例中的数据。这是教程 https://www.php.net/manual/en/function.array-multisort.php

这个问题之后我的下一步是根据数据的键值对数据进行排序。 请帮忙。或者您可以选择其他选项来对我的数据进行排序而不进行转换?

【问题讨论】:

  • json_decode( $data, true ) ?将解码后的数据作为多维数组返回
  • 也已经尝试$decode = json_decode(json_encode($data), true);,但它返回相同的数据。 @ProfessorAbronsius

标签: php arrays json object lumen


【解决方案1】:

读取数据

$unsortedData = json_decode(file_get_contents("data.json"), true);

第二个参数 true 让你得到一个关联数组,而不是得到一个对象数组(stdclass)

对数组进行排序:

usort($unsortedData,  function($a, $b){
    return $a['serial'] < $b['serial'];
});

usort会根据作为第二个参数传递的回调对数据进行排序,所以你可以自定义它

【讨论】:

  • 谢谢,我试试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 2023-03-12
  • 2020-06-08
  • 2023-03-06
相关资源
最近更新 更多