PHP 在前面加上一个数组



通过使用下面的 PHP 输出下面的值。但是由于我无法控制 API 输出,因此我想尝试在数据前面加上另一个输出,例如{"id":0,"name":"Begin","description":"this is my description","url":"http://domain.com"}

有人可以帮忙吗?

.PHP

<?php
$jsonurl = "/api/styles";
$json = file_get_contents($jsonurl);
echo $json;
?>

输出

[{"id":1,"name":"Pale","description":"this is my description","url":"http://domain.com"},{"id":2,"name":"Dawn","description":"this is my description","url":"http://domain.com"}]

这是你的想法吗?

<?php
$jsonurl = "/api/styles";
$json = file_get_contents($jsonurl);
$json = '[{"id":0,"name":"Begin","description":"this is my description","url":"http://domain.com"},' . substr($json, 1);
echo $json;
?>

输出:

[{"id":0,"name":"Begin","description":"this is my description","url":"http://domain.com"},{"id":1,"name":"Pale","description":"this is my description","url":"http://domain.com"},{"id":2,"name":"Dawn","description":"this is my description","url":"http://domain.com"}]
$jsonurl = "/api/styles";
$json = file_get_contents($jsonurl);
$begin = '{"id":0,"name":"Begin","description":"this is my description","url":"http://domain.com"}';
$data = json_decode($json);
array_unshift($data, json_decode($begin));
echo json_encode($data);

如果它真的是 json,请解析它 (decode_json()) 并随心所欲地打印它。

我不确定你想要"预置"什么,但你可以把它变成一个PHP数组,反转它,然后将新元素推送到数组上。

$json = file_get_contents($jsonurl);
$array = json_decode($json, true);
$reversed = array_reverse( $array );
$reversed[] = ['id' => 0, 'name' => 'Something];

将其反转并对其进行编码。

最新更新