M
M
Marten2022-03-26 17:02:22
PHP
Marten, 2022-03-26 17:02:22

PHP Return Array from API?

Good afternoon, thank you all for your replies.

I have similar PHP code. I need to return it via something like [Return] because [Echo] outputs the code before the html code no matter where you put the shortcode - but it's logical. But I don’t understand how I can do this, if I get a large asynchronous array from the API and, say, setting a value for each variable is not entirely realistic, especially since I iterate through foreach and add the output conditions for this enumeration (that is, I don’t have some of the necessary information infers). I understand that you can saddle Return array (), but I do not understand what I should write in array if I cannot set values ​​for variables. There is a [List] option, but here I really can’t understand the logic of its work.

<?php

...

$data2 = json_decode($response2, true, 999, JSON_THROW_ON_ERROR);

$a = 1;$b = 1;
foreach ($data2 as $reposit2): if($reposit2['import_export_and_transit_procedures'] ?? $reposit2['enquiry_points'] ?? $reposit2['single_window']):
echo '<div class="collage-thumb"><a href="#" class="js-open-modal image-link" data-modal="'.$a++.'"><img src="/wp-content/uploads/agora/img/flag/flag'.$reposit2['id'].'.jpg" alt="img" /><div class="thumb-info">'.$reposit2['name'].'</div></a></div>'; 
else:
    echo "";
endif;
endforeach;

...


It's just bullshit
<?php
$content '<div class="collage-thumb"><a href="#" class="js-open-modal image-link" data-modal="'.$a++.'"><img src="/wp-content/uploads/agora/img/flag/flag'.$reposit2['id'].'.jpg" alt="img" /><div class="thumb-info">'.$reposit2['name'].'</div></a></div>';
return array($content,) 

or

list($content)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nokimaro, 2022-03-27
@Martenek

1. Put the results echoin a variable
instead 2. Display the results in the right places
3. Keep learning programming, don't listen to anyone

//изначальное состояние - пустая строка
$content = ""; 
foreach ($data2 as $reposit2) {
    //добавляем содержимое в цикле
    $content .= '<div class итд';
}

//в нужном месте
echo $content;

If we do something inside the function return $content;- that is, we return a string with pieces of html and then use this result at our discretion.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question