花了几个小时阅读,研究,并且无法弄清楚,这是我的代码:
<?php
$userid = "";
$accessToken = "";
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}&count=-1");
$result = json_decode($result);
?>
<?php foreach ($result->data as $post):{
if (stripos($post->caption->text,'egypt') !== false) {
unset($post);
$post = (str_split($post->caption->text));
$post = (array_filter($post));
}
}
?>
<img src="<?= $post->images->low_resolution->url?>" />
<?= $post->caption->text ?>
<?php endforeach ?>
正如你所看到的那样,我正试图用#34; egypt&#34;在他们中提到,我通过使用unset成功地做到了这一点。但是,即使使用array_filter,我仍然会获得空元素。对于埃及照片,HTML看起来像这样:<img src="" />
(你可以想象)。
这是我不理解的:
<?php foreach ($result->data as $post):
{
if (stripos($post->caption->text,'egypt') !== false) {
}
else{
unset($post);
$posta = (str_split($post->caption->text));
$posta = (array_filter($post));
$posta = array_filter($posta, 'strlen' );
}
}
?>
<img src="<?= $post->images->low_resolution->url?>" /><br>
<?= $post->caption->text ?><br><br>
<?php endforeach ?>
给我我想要的结果(只有埃及照片和描述),但它也给我一个PHP错误:Warning: array_filter() expects parameter 1 to be array, null given' and
警告:array_filter()期望参数1是数组,null给定`isn&# 39; t array_filter应该删除空值?我只想用什么都没有替换错误。
答案 0 :(得分:0)
你可以使用带有回调函数的array_filter,如strlen,这将删除NULL,空字符串,FALSE和false表示显式为FALSE而不是0
$result = array_filter( $array, 'strlen' );
答案 1 :(得分:0)
我建议将循环更改为以下内容:
只有在埃及&#39;还没有找到。
<?php foreach ($result->data as $post){
if (stripos($post->caption->text,'egypt') === false) {
$post = (str_split($post->caption->text));?>
<img src="<?= $post->images->low_resolution->url?>" />
<?= $post->caption->text ?>
<?php
}
else{
unset $post;
}
?>
或者,您可以先在一个循环中清理数组,然后在另一个循环中打印您的条目。这可能会更容易添加额外的过滤器&#39;后面。
<?php
//edit --- typos clean_aray = array();
$clean_array = array();
foreach ($result->data as $post){
if (stripos($post->caption->text,'egypt') === false) {
$clean_array[] = $post;
}
}
foreach ($clean_array as $post){
$post = (str_split($post->caption->text));?>
<img src="<?= $post->images->low_resolution->url?>" />
<?= $post->caption->text ?>
<?php
}
?>