douqihua6212 2016-12-01 22:51
浏览 59
已采纳

PHP检查项目是否存在于数组中然后返回值 - 转换为函数

Working on a WordPress site and using Advanced Custom Fields. I am looping through an flexible content array and creating an array from the return.

The issue is I need to return differently named images in an array but the images might be null (they can be empty).

This currently works:

"images" => [
    "image_one"   => ( $l['image_one']['url'] ? $l['image_one']['url'] : NULL ),
    /* etc */
]

But this is in a switch statement so I wanted to be able to pass the:

$l['image_one']['url']

To a function and only return the URL if there is one. However I could have a array where $l['image_three']['url'] is not set and not in the array returned so I will always get undefined offset notices.

I can carry on the way I am but its getting repetive and would rather be able to do e.g.:

 "image_one" => imageExists($l['image_one']['url'])

But of course I am already calling a key that doesn't exist (possibly). Is there an other methods of tidying up my shorthand if?

  • 写回答

2条回答 默认 最新

  • doushi7761 2016-12-01 23:00
    关注

    Use isset() on your ternary condition:

    function imageExists($image) {
        return isset($image['url']) ? $image['url'] : NULL;
    }
    

    And invoke with:

    imageExists($l['image_one']);
    

    If you're on a version >= PHP 7.0, you can use the null coalescing operator (search here.) For:

    function imageExists($image) {
        return $image['url'] ?? NULL;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效