英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论