I would like some advices to optimise my PHP code, I'm using an API and sometime it return one result or an array of results like this :
我想要一些优化PHP代码的建议,我正在使用一个API,有时它会返回一个结果或像这样的结果数组:
First possibility :
第一个可能性:
Array
(
[collection] => Array
(
[links] => Array
(
[id] => 1
[url] => www.google.fr
)
)
)
or Second possibility :
或第二种可能性:
Array
(
[collection] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[url] => www.google.fr
)
[1] => Array
(
[id] => 2
[url] => www.google.fr
)
[2] => Array
(
[id] => 3
[url] => www.google.fr
)
)
)
)
How can I optimise my code for this case ?
我该如何优化我的代码呢?
$url = '';
$nb_results = count($array['collection']['links']);
if($nb_results == 1){
$url .= $array['collection']['links']['url'];
} else {
foreach( $array['collection']['links'] as $r){
$url .= $r['url'].'<br />';
}
}
1 个解决方案
#1
4
If API returns only one result, make an array from this result and use foreach. Thanks to that you don't need to have use if..else
when creating $url
variable. Look at this code:
如果API只返回一个结果,那么从这个结果创建一个数组并使用foreach。因为你不需要用if.. .当创建$url变量时。看看这段代码:
// checking if links is array; if not - make array with one returned element from API
$data = isset($array['collection']['links'][0]) ? $array['collection']['links'] : array($array['collection']['links']);
foreach( $data as $r)
{
$url .= $r['url'].'<br />';
}
#1
4
If API returns only one result, make an array from this result and use foreach. Thanks to that you don't need to have use if..else
when creating $url
variable. Look at this code:
如果API只返回一个结果,那么从这个结果创建一个数组并使用foreach。因为你不需要用if.. .当创建$url变量时。看看这段代码:
// checking if links is array; if not - make array with one returned element from API
$data = isset($array['collection']['links'][0]) ? $array['collection']['links'] : array($array['collection']['links']);
foreach( $data as $r)
{
$url .= $r['url'].'<br />';
}