doutangxi2144 2018-05-11 10:07
浏览 58
已采纳

PHP数组 - 删除空元素,只获取填充的字符串

I have the following array in PHP, which I'm pulling from a JSON file. I've tried carrying out a foreach to fetch only the supplier names, but to no avail.

Ideally, I'd like to just return CB DESIGN and DESIGN COMPANY but any time I've tried this, it either returns the following:

array(4322)
    [0]=> array(1) {["supplier"]=> array(0) { }}
    [1]=> array(1) {["supplier"]=> array(0) { }}
    [2]=> array(1) {["supplier"]=> array(0) { }}
    [3]=> array(1) {["supplier"]=> array(1) {[0]=> string(29) " CB DESIGN "}}
    [4]=> array(1) {["supplier"]=> array(1) {[0]=> string(19) " DESIGN COMPANY "}}

I only want to return the company names, is there any way to strip out the empty elements, I've tried using array_filter but it keeps returning the same, as above.

Any help would be greatly appreciated.

Many thanks!

  • 写回答

1条回答 默认 最新

  • doufeng5059 2018-05-11 10:17
    关注

    You probably misused the array_filter.

    This code returns only elements with non-empty supplier

    Input:

    $arr = [
        ["supplier" => []],
        ["supplier" => []],
        ["supplier" => []],
        ["supplier" => [" CB DESIGN "]],
        ["supplier" => [" DESIGN COMPANY "]],
    ];
    
    $arrFiltered = array_filter($arr, function($item) {
        return !empty($item["supplier"]);
    });
    

    Output:

    array(2) {
      [3]=>
      array(1) {
        ["supplier"]=>
        array(1) {
          [0]=>
          string(11) " CB DESIGN "
        }
      }
      [4]=>
      array(1) {
        ["supplier"]=>
        array(1) {
          [0]=>
          string(16) " DESIGN COMPANY "
        }
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?