首页 > 解决方案 > 如何删除具有重复列值的子数组?

问题描述

我有一个这样的数组-

Array
(
    [0] => Array
        (
            [size] => 12" x 24"
            [size_description] => <p>Rectified</p>

        )

[1] => Array
    (
        [size] => 12" x 24"
        [size_description] => <p>Rectified</p>

    )

[2] => Array
    (
        [size] => 24" x 24"
        [size_description] => <p>Rectified</p>

    )

[3] => Array
    (
        [size] => 24" x 24"
        [size_description] => <p>Rectified</p>

    )

[4] => Array
    (
        [size] => 24" x 48"
        [size_description] => <p>Rectified</p>

    )

[5] => Array
    (
        [size] => 24" x 48"
        [size_description] => <p>Rectified</p>

    )

)

我想获得基于“大小”的不同子数组,我可以循环大小和 size_description。我尝试了无法正常工作的array_unique,我只得到一个值,即大小。我尝试的是

$new_array = array_unique(array_map(function($elem){return $elem['size'];}, $size_array));

我想同时获得这两个值。有没有办法做到这一点?

标签: phparraysforeachunique

解决方案


这会给你想要的结果

$newArr = array();

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

   if(!in_array($value['size'], $newArr))
    $newArr[$value['size']] = $value;

  }

结果:-

 Array
(
  [12" x 24"] => Array
    (
        [size] => 12" x 24"
        [size_description] => Rectified


    )

[24" x 24"] => Array
    (
        [size] => 24" x 24"
        [size_description] => Rectified


    )

[24" x 48"] => Array
    (
        [size] => 24" x 48"
        [size_description] => Rectified


    )

)

推荐阅读