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

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

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

 { "result": [
    548915,
    505031,
    28967,
    520928,
    441762,
    381418,
    61650,
    249457,
    535995,
    550023,
      and more.. and more.. and more..  ]
}

I want to change it to be like this

{ 
    "result": [
        {"id": 548915,}, 
        {"id": 505031,}, 
        {"id": 28967,},
        {"id": 28967,}, 
        {"id": 28967,}
      ] 
}

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

 { "result": [
    548915,
    505031,
    28967,
    520928,
    441762,
    381418,
    61650,
    249457,
    535995,
    550023,
      and more.. and more.. and more..
   ]
}

I want to change it to be like this

{ 
    "result": [
        {"id": 548915,}, 
        {"id": 505031,}, 
        {"id": 28967,},
        {"id": 28967,}, 
        {"id": 28967,}
      ] 
}

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字符串。

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

结果:

[
    {
        "id": 548915
    },
    {
        "id": 505031
    },
    {
        "id": 28967
    },
    // ...
]

你可以跳过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

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

RESULTS

[
    {
        "id": 548915
    },
    {
        "id": 505031
    },
    {
        "id": 28967
    },

    . . .

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:

确定