如何在php中使用值创建唯一键

ej83mcc0  于 2023-01-19  发布在  PHP
关注(0)|答案(2)|浏览(132)

我正在使用laravel框架来开发API。我在一个点上卡住了,我有一个带有重复键和随机值的数组,如下所示

array:35 [
  0 => array:1 [
    "Contact Info" => 75
  ]
  1 => array:1 [
    "Contact Info" => 76
  ]
  2 => array:1 [
    "Contact Info" => 77
  ]
  3 => array:1 [
    "Contact Info" => 78
  ]
  4 => array:1 [
    "Contact Info" => 79
  ]

  12 => array:1 [
    "Contact Info" => 596
  ]
  13 => array:1 [
    "Contact Info" => 597
  ]
  14 => array:1 [
    "Contact Info" => 593
  ]
  15 => array:1 [
    "Contact Info" => 595
  ]
  16 => array:1 [
    "Contact Info" => 588
  ]
  17 => array:1 [
    "Contact Info" => 594
  ]
  18 => array:1 [
    "Contact Info" => 591
  ]
  19 => array:1 [
    "Contact Info" => 592
  ]
  20 => array:1 [
    "Contact Info" => 626
  ]
  21 => array:1 [
    "Contact Info" => 590
  ]
  22 => array:1 [
    "Address Info" => 85
  ]
  23 => array:1 [
    "Address Info" => 86
  ]
  24 => array:1 [
    "Address Info" => 87
  ]
  
]

我想要上面像下面的数组,注意数组键将是动态的,而不是静态的。谁能帮我实现这一个。

$temp = ['contact Info' => ['75','76',77',78'....] ,'Address Info' =. ['85','86','87'...]];
lndjwyie

lndjwyie1#

如果您的密钥也是动态的,您可以尝试以下代码:

$temp = [];
    foreach ($array as $item) {
        foreach ($item as $key => $itemValue) {
            $temp[$key][] = $itemValue;
        }
    }

print_r($temp);

希望它有助于arrray_column()解决方案在非动态的情况下更有效。

kmbjn2e3

kmbjn2e32#

你可以将这些进行分组,并在完成时进行唯一性和排序.

<?php

$data = [
    [
            "Contact Info" => 5
        ],
        [
            "Address Info" => 85
        ],
    [
            "Address Info" => 885
        ],
    [
            "Contact Info" => 592
        ],
    [
            "Address Info" => 85
        ],
    [
        "Address Info" => 8
        ],
    [
            "Contact Info" => 3
        ],
            [
            "Contact Info" => 3
        ],
    
    ];
$dumpData = ['Contact Info'=>array_unique(array_column($data,'Contact Info')),'Address Info'=> array_unique(array_column($data,'Address Info'))];
sort($dumpData['Contact Info']);
sort($dumpData['Address Info']);

echo'<pre>';

print_r($dumpData);

https://onlinephp.io/c/e6125

相关问题