如何在PHP中将JSON值更改为名称和值?

huangapple go评论100阅读模式
英文:

How to change JSON Value to Name and Value? in PHP

问题

I have List of IDs in JSON

Here it is: https://temp.9animetv.live/api.php

it look like this

  1. { "result": [
  2. 548915,
  3. 505031,
  4. 28967,
  5. 520928,
  6. 441762,
  7. 381418,
  8. 61650,
  9. 249457,
  10. 535995,
  11. 550023,
  12. and more.. and more.. and more.. ]
  13. }

I want to change it to be like this

  1. {
  2. "result": [
  3. {"id": 548915,},
  4. {"id": 505031,},
  5. {"id": 28967,},
  6. {"id": 28967,},
  7. {"id": 28967,}
  8. ]
  9. }

How to do that? Am using PHP

I have Tried

To change it to Array using Json_decode But still haven't figured out a way to do as I expected.

英文:

I have List of IDs in JSON

Here it is: https://temp.9animetv.live/api.php

it look like this

  1. { "result": [
  2. 548915,
  3. 505031,
  4. 28967,
  5. 520928,
  6. 441762,
  7. 381418,
  8. 61650,
  9. 249457,
  10. 535995,
  11. 550023,
  12. and more.. and more.. and more..
  13. ]
  14. }

I want to change it to be like this

  1. {
  2. "result": [
  3. {"id": 548915,},
  4. {"id": 505031,},
  5. {"id": 28967,},
  6. {"id": 28967,},
  7. {"id": 28967,}
  8. ]
  9. }

How to do that? Am using PHP

I have Tried

To change it to Array using Json_decode But still haven't figured out a way to do as I expected

答案1

得分: 1

只需读取JSON字符串,使用json_decode()将其转换为PHP等效对象,处理ID数组并创建一个新数组,然后将其再次转换为JSON字符串。

  1. $j_str = file_get_contents('https://temp.9animetv.live/api.php');
  2. $j_arr = json_decode($j_str);
  3. $new = [];
  4. foreach ($j_arr->result as $occ) {
  5. $new[] = ['id' => $occ];
  6. }
  7. echo json_encode($new);

结果:

  1. [
  2. {
  3. "id": 548915
  4. },
  5. {
  6. "id": 505031
  7. },
  8. {
  9. "id": 28967
  10. },
  11. // ...
  12. ]

你可以跳过JSON_PRETTY_PRINT,那只是为了方便阅读输出以进行检查。

英文:

Simply read the json string, convert it to a PHP equivalent object using json_decode()
process the array of id's and create a new array which you then convert back to a JSON String

  1. $j_str = file_get_contents('https://temp.9animetv.live/api.php');
  2. $j_arr = json_decode($j_str);
  3. $new = [];
  4. foreach ( $j_arr->result as $occ ) {
  5. $new[] = ['id' => $occ];
  6. }
  7. echo json_encode($new, JSON_PRETTY_PRINT);

RESULTS

  1. [
  2. {
  3. "id": 548915
  4. },
  5. {
  6. "id": 505031
  7. },
  8. {
  9. "id": 28967
  10. },
  11. . . .

You can skip the , JSON_PRETTY_PRINT, thats only I could easily read the output for checking

huangapple
  • 本文由 发表于 2023年3月9日 21:31:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685292.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定