I am using PHP curl to get data from an API. I want to print main heading only 1 time, but now it is printing more than one time if there is .. Following is my code.
I want the results as in following structure
Marketing
- Technical writer USA. read more link
- Technical writer USA. read more link
Now am getting data as
Marketing
Technical writer USA. read more link
Marketing
Technical writer kakandu. read more link
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.example.com/c/1832/offers",
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",
"Authorization: Bearer R0ssstYYXBTWG1Ddm5wbUgzT3pwa214Zz09"
),
));
$response = json_decode(curl_exec($curl));
curl_close($curl);
?>
<?php
// echo "<pre>";
// var_dump($response);
foreach($response->offers as $key=>$value){
echo '<div>
<h1><u>'.$value->department.'</u></h1> <br>
<p>'.$value->title.'</p><br>
<p>'.$value->location.'</p>
<a target="_blank" href='.$value->url.'>Read More </a>
</div>';
}
?>
</body>
</html>
Kindly help me
My Answer:
It seems like the issue is with how you are looping through the data and printing the main heading. You can modify your code to only print the main heading once by checking if it has already been printed before. Here's an example of how you can achieve this:
php
// Sample data
$data = [
['category' => 'Marketing', 'title' => 'Technical writer USA', 'link' => 'read more link'],
['category' => 'Marketing', 'title' => 'Technical writer kakandu', 'link' => 'read more link'],
];
$printedMainHeading = false;
foreach ($data as $item) {
if (!$printedMainHeading) {
echo $item['category'] . "
";
$printedMainHeading = true;
}
echo $item['title'] . ". " . $item['link'] . "
";
}
?>
This code will only print the main heading once and then print the title and link for each item in the data array. Make sure to replace the sample data with the actual data you are getting from the API.
Rate this post
4 of 5 based on 8813 votesComments