简体   繁体   English

将 arrays 数组转换为具有唯一值的逗号分隔列表 - PHP

[英]convert array of arrays into comma separated list with unique values - PHP

I have an array that looks like below:我有一个如下所示的数组:

$var[] =   ^ array:4 [▼
      0 => array:1 [▼
        0 => "apple"
      ]
      1 => array:1 [▼
        0 => "apple"
        1 => "grape"
      ]
      2 => array:1 [▼
        0 => "orange"
      ]
      3 => array:1 [▼
        0 => "banana"
      ]
    ]

Is there a way to convert this array into comma separated list with unique values as below?有没有办法将此数组转换为具有唯一值的逗号分隔列表,如下所示?

$var = "apple,grape,orange,banana"

I tried implode(', ',$var) but it's not working as expected.我试过 implode(', ',$var) 但它没有按预期工作。 Any help pls?有什么帮助吗?

Update: My sub-array may have more than 1 element.更新:我的子数组可能有超过 1 个元素。 It's dynamic.它是动态的。

This produces the results given the expected input.在给定预期输入的情况下,这会产生结果。 Basically array_column get's the first item from each item of the array (0 based).基本上array_column从数组的每个项目中获取第一项(基于 0)。 Then array_unique on that will simply get the values without duplicates.然后array_unique将简单地获取没有重复的值。

$arr = [
    ['apple'],
    ['apple'],
    ['banana'],
    ['pie'],
];

print_r(array_unique(array_column($arr, 0)));

There's also a one-liner solution:还有一个单行解决方案:

$result= array_unique(call_user_func_array('array_merge', $arr));

cf.参看。 https://stackoverflow.com/a/14972714/13720553 https://stackoverflow.com/a/14972714/13720553

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM