i tried to pull the categories in Json but couldn't succeed. i was able to get other fields easily. i tried several foreach intertwined but failed.
JSON example
{
"MainUnit": "1",
"ProductCategory": {
"ID": 160,
"Name": "Basketball",
"MainCategory": false,
"ParentCategoryID": 152,
"ParentCategory": {
"ID": 152,
"Name": "Football",
"MainCategory": false,
"ParentCategoryID": 2,
"ParentCategory": {
"ID": 2,
"Name": "SPORT",
"MainCategory": true,
"ParentCategory": null,
"ParentCategoryID": 0
}
}
"Brand": "Spect"
},
}
....
json outputs come in order like this...
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://example.com/json/sports',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer gd6yaw7gjiLQ8VeytrpLrl9mzU0oUx4966D61PdbuYVrCU178E'
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
foreach($response as $return){
foreach($return->ProductCategory as $categories){
if ($categories != null) {
echo $categories->ID.'<br />';
echo $categories->Name.'<br />';
}
foreach($categories->ParentCategory as $categorie){
if ($categorie->parentCategory != null) {
echo $categorie->ID.'<br />';
echo $categorie->Name.'<br />';
echo $categorie->MainCategory.'<br />';
echo $categorie->ParentCategoryID.'<br />';
}else{
echo $categorie->ID.'<br />';
echo $categorie->Name.'<br />';
echo $categorie->MainCategory.'<br />';
echo $categorie->ParentCategoryID.'<br />';
}
foreach($categorie->ParentCategory as $category){
if ($category->parentCategory != null) {
echo $category->ID.'<br />';
echo $category->Name.'<br />';
echo $category->MainCategory.'<br />';
echo $category->ParentCategoryID.'<br />';
}else{
echo $category->ID.'<br />';
echo $category->Name.'<br />';
echo $category->MainCategory.'<br />';
echo $category->ParentCategoryID.'<br />';
}
}
}
}
}
I pull the json data with the curl method as above, and solve it with json_decode. How can I pull categories in a healthy way?
question from:
https://stackoverflow.com/questions/65902480/getting-an-error-when-trying-to-pull-categories-from-a-json 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…