花了几个小时阅读、研究,却弄不明白,这是我的代码:
<?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 ?>
正如你所看到的,我正试图消除其中提到的"埃及"的回复,我通过使用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是array,null给定`array_filter不应该删除null值吗?我只想用任何东西来代替这些错误。
我建议将循环更改为以下内容:
只有在找不到"埃及"时才打印出来。
<?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;
}
?>
或者,您可以先在一个循环中清理数组,然后在另一个循环打印条目。这可能会使以后更容易添加额外的"筛选器"。
<?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
}
?>
您可以将array_filter与strlen这样的回调函数一起使用,这将删除NULL、空字符串和FALSE,我所说的FALSE是指明确地为FALSE而不是0
$result = array_filter( $array, 'strlen' );