使用 PHP 将文本添加到 JSON 数组中的特定元素
Add Text to a particular element in JSON array with PHP
我想向数组中的特定元素添加额外的文本,
从输入下方,我想将 "Image":"12001116" 更改为 "Image":"wp-content/upload/12001116.jpg".
所以我想添加 "wp-content/upload/" $value['Image']; “.jpg”
有人可以帮忙吗!
输入
$json = '[
{
"Image":"12001116",
"Name":"Jean-Marc",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"44.343518",
"LONGITUDE":"2.716004"
},
{
"Image":"1200558",
"Name":"Aurélien ",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"42.343828",
"LONGITUDE":"2.920056"
}
]';
并且输出应该是
$json = '[
{
"Image":"wp-content/upload/12001116.jpg",
"Name":"Jean-Marc",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"44.343518",
"LONGITUDE":"2.716004"
},
{
"Image":"wp-content/upload/1200558.jpg",
"Name":"Aurélien ",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"42.343828",
"LONGITUDE":"2.920056"
}
]';
您可以使用array_map()
循环对象:
$json = json_decode($input); // $input is the JSON input string
$newJson = array_map(function ($obj) {
$obj->Image = 'wp-content/upload/' . $obj->Image . '.jpg';
return $obj;
}, $json);
$output = json_encode($newJson, JSON_PRETTY_PRINT);
echo $output; // done!
编辑:
如果您不想要反斜杠 \
,则将第 6 行更改为:
$output = json_encode($newJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
我想向数组中的特定元素添加额外的文本, 从输入下方,我想将 "Image":"12001116" 更改为 "Image":"wp-content/upload/12001116.jpg".
所以我想添加 "wp-content/upload/" $value['Image']; “.jpg” 有人可以帮忙吗!
输入
$json = '[
{
"Image":"12001116",
"Name":"Jean-Marc",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"44.343518",
"LONGITUDE":"2.716004"
},
{
"Image":"1200558",
"Name":"Aurélien ",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"42.343828",
"LONGITUDE":"2.920056"
}
]';
并且输出应该是
$json = '[
{
"Image":"wp-content/upload/12001116.jpg",
"Name":"Jean-Marc",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"44.343518",
"LONGITUDE":"2.716004"
},
{
"Image":"wp-content/upload/1200558.jpg",
"Name":"Aurélien ",
"CODE_POSTAL":"12630 ",
"VIL":"AGEN D AVEYRON",
"LATITUDE":"42.343828",
"LONGITUDE":"2.920056"
}
]';
您可以使用array_map()
循环对象:
$json = json_decode($input); // $input is the JSON input string
$newJson = array_map(function ($obj) {
$obj->Image = 'wp-content/upload/' . $obj->Image . '.jpg';
return $obj;
}, $json);
$output = json_encode($newJson, JSON_PRETTY_PRINT);
echo $output; // done!
编辑:
如果您不想要反斜杠 \
,则将第 6 行更改为:
$output = json_encode($newJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);