为了账号安全,请及时绑定邮箱和手机立即绑定

PHP/Laravel - 从键有数据的数组中获取键名称

PHP/Laravel - 从键有数据的数组中获取键名称

PHP
月关宝盒 2023-10-22 22:04:18
我有以下数组$items:array:3 [▼  0 => array:9 [▼    "qty" => 1    "name" => "Guide, interlocked slats, R Commodity code: 39239000 / Country of origin: PL. Delivery note 838174147 from 12.09.2019 PC 1,50/ 10"  ]  1 => array:9 [▼    "qty" => null    "name" => "Guide, interlocked slats, L Commodity code: 39239000 / Country of origin: PL. Delivery note 838174147 from 12.09.2019 PC"  ]  2 => array:9 [▼    "qty" => null    "name" => "Bottom groove set L + R Commodity code: 39239000 / Country of origin:"  ]]我试图找到在所有三个子数组中都有值的特定键。在本例中,这将是 key name,因为该特定键在所有三个数组中都有一个值。我尝试为此编写一个函数,如下所示:function getKeysWithData(array $items): array{    //Get the key(s) that has region data for all items.    $keysWithData = collect($items)->map(function ($item) {        return array_keys(collect($item)->filter()->toArray()); //filter will remove all null    })->flatten()->unique()->toArray();   }上面的函数返回一个数组,其中包含具有某些值的键的名称。所以对于上面的$items,它将返回:array:2 [▼  0 => "qty"  1 => "name"]这是因为 和 两者qty在name某些时候都包含一些价值。但是,它应该只返回name.我该怎么做,所以它只会返回所有数组中都有数据的键的名称?
查看完整描述

2 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

虽然这不是 Laravel 和所有这些函数式风格,但至少它只在数组上循环一次:


// Take first element so as to know what keys do we have:

$keys = $items[0];

foreach ($items as $item) {

    foreach ($item as $key => $value) {

        if ($value === null) {

            // unset the key which has NULL value

            unset($keys[$key]);

        }

        

        // if there no keys left - break all loops

        if (empty($keys)) {

            break 2;

        }

    }

}

print_r(array_keys($keys));

还有小提琴



查看完整回答
反对 回复 2023-10-22
?
慕姐8265434

TA贡献1813条经验 获得超2个赞

对二维数组使用两次 foreach 循环。前任: '''


       foreach($array as $k=>$v){

        //$k is 0

        //$v contains another inside array so use another foreach loop

         foreach($v as $x => $y){

    

       if($y != "null" && $x != "null" && $x == "name"){

    echo $x;  //it contains key ex : name

    echo $y;  //it contains value ex : 1

   $z[$x]=$y; // it contains only name key

    }

          

        }

        

        }

'''


查看完整回答
反对 回复 2023-10-22
  • 2 回答
  • 0 关注
  • 75 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信