【发布时间】:2019-09-19 15:08:04
【问题描述】:
我这几天一直在敲我的脑袋,我希望比我聪明得多的人(这并不难,因为我是一个完全的新手)能够阐明我的问题。 我有来自不同 API 的 json 数据,第一个 API 为我提供了产品列表和每个产品单独 API 的路由,然后我使用这些 API 获取数据并将其解码为 wordpress 中的 PHP 多维数组。我需要按特定顺序提取值并添加 html 格式,然后将它们返回到字符串中。
这是我的已解码为数组的 json 提要的简化表示,第一个是我从中提取 API 地址的 json:
{
"data": [
{
"product": "Product A",
"api": "some/api/feeda",
"catagory": "some catagory"
},
{
"product": "Product B",
"api": "some/api/feedb",
"catagory": "other catagory"
}
]
}
然后检索第二个并返回产品 json:
{
"data": {
"title": "Product A",
"catagory": "Catagory 1",
"specifications": [
{
"detail": "Technical detail 1",
"notes": "",
"subDetails": [
{
"width": "A not so wide version",
"height": "This one is shorter"
},
{
"width": "a wider version",
"height": "a taller version"
}
]
},
{
"detail": "Technical detail 2",
"notes": "a little bit about detail 2 that is different"
},
{
"detail": "Technical detail 3",
"notes": "something boring to do with detail 3"
}
]
}
}
我的目标是仅从选定的类别生成帖子,并使用从“规范”(注释和子详细信息)中提取的标题和 html 格式的内容填充它,以便帖子的内容看起来像这样:
<b>Technical detail 1</b>
A not so wide version
a wider version<br>
<b>Technical detail 2</b>
a little bit about detail 2 that is different<br>
<b>Technical detail 3</b>
something boring to do with detail 3<br>
在我开始使用“wp_insert_post”创建一大堆我不想要的帖子之前,我正在使用“echo”,这样我就可以看到我得到了什么结果。我在 PHP 方面已经做到了这一点,并设法为每个产品标题创建了一个列表,但我尝试的其他方法均无效(我确实设法在列表中获得了产品规格,但它们是错误的规格!)
function product_list($productlist$) {
$url_request = wp_remote_get('https://main/api/products/v1/all');
if (is_wp_error($url_request)) {
return false; // Bail early
}
$body = wp_remote_retrieve_body($url_request);
$url_json = json_decode($body, true);
$url_data = $url_json['data'];
if (!empty($url_data)) {
foreach($product_url as $product) {
$singleproduct_url = $product["url"];
$singleproduct_urlrequest = wp_remote_get('https://main/api/products/v1'.$single_product_url.
'');
$singleproduct_body = wp_remote_retrieve_body($singleproduct_urlrequest);
$singleproduct_json = json_decode($singleproduct_body, true);
$singleproduct_data = $singleproduct_json['data'];
$productspecs = $singleproduct_data['specifications'];
foreach($productspecs as $productspec) {
$specdetail = "<br>".$productspec["detail"];
$subdetails = $productspec['subDetails']
if (!empty($productspec['note'])) {
$productnote = $productspec['note'];
} else {
foreach($subdetails as $subdetail) {
$subdetailtext = $subdetails[width];
}
};
echo '<li>';
echo $singleproduct_data["title"];
echo $productnote;
echo '</li>';
}
echo '</ul>';
}
}
任何帮助将不胜感激!!!
【问题讨论】:
-
$productlist$不是有效标识符。你循环未定义的变量$product_url。我不会再看下去了。
标签: php json wordpress multidimensional-array