从PHP中的嵌套数组中删除元素

时间:2019-04-24 07:41:47

标签: php arrays multidimensional-array associative-array

我正在使用Laravel应用程序,通过该数组我可以将一个关联数组传递给API端点。在发布到API之前,我我要删除img键及其值。我尝试使用取消设置功能,但未删除img键

我要删除图片属性的数组

 $a[] = [
  0 => array:4 [
    "name" => "Martoo nnn"
    "relationship" => "Spouse"
    "dob" => "2001-02-03"
    "img" => "img.png"
  ]
  1 => array:4 [
    "name" => "sdsdsd sdsdsd"
    "relationship" => "Child"
    "dob" => "2019-04-04"
    "img" => "img1.png"
  ]
  2 => array:4 [
    "name" => "sdsdsd sddds"
    "relationship" => "Child"
    "dob" => "2019-04-05"
    "img" => "img2.png"
  ]
  3 => array:4 [
    "name" => "dssdsd dsdsd"
    "relationship" => "Child"
    "dob" => "2019-04-02"
    "img" => "img3.png"
  ]
  4 => array:4 [
    "name" => "dssdsd dssdsd"
    "relationship" => "Child"
    "dob" => "2019-04-04"
    "img" => "img4.png"
  ]
];

未设置方法

$array = $a;
unset($array['img']);

//dd($a);

2 个答案:

答案 0 :(得分:2)

您可以这样做,

foreach ($array as $key => &$value) { // & defines changes will be made @ value itself
    unset($value['img']);
}

是的,我不明白您为什么将$a初始化为$a[]

答案 1 :(得分:0)

O(|filter| * |notes|)

并传递这个新数组