从二维数组中的列获取唯一值

发布于 2024-11-08 21:03:14 字数 866 浏览 0 评论 0原文

我有一个二维数组,需要将唯一的列与一列隔离开。

$array = [
    [..., 'key' => 1, ...],
    [..., 'key' => 2, ...],
    [..., 'key' => 3, ...],
    [..., 'key' => 1, ...],
    [..., 'key' => 2, ...],
    [..., 'key' => 3, ...],
    [..., 'key' => 4, ...],
    [..., 'key' => 5, ...],
    [..., 'key' => 6, ...]
];

仅当元素尚不存在时,如何将它们添加到结果数组中?我有以下内容:

$a = [];
// organize the array
foreach ($array as $k => $v) {
    foreach ($v as $key => $value) {
        if ($key == 'key') {
            $a[] = $value;
        }
    }
}
print_r($a);

输出:

Array
(
  [0] => 1
  [1] => 2
  [2] => 3
  [3] => 1
  [4] => 2
  [5] => 3
  [6] => 4
  [7] => 5
  [8] => 6
)

相反,我希望 $a 由唯一值组成。 (我知道我可以在循环后使用 array_unique() 来获得所需的结果,但我只想知道任何其他方法。)

I have a 2d array and need to isolate the unique columns from one column.

$array = [
    [..., 'key' => 1, ...],
    [..., 'key' => 2, ...],
    [..., 'key' => 3, ...],
    [..., 'key' => 1, ...],
    [..., 'key' => 2, ...],
    [..., 'key' => 3, ...],
    [..., 'key' => 4, ...],
    [..., 'key' => 5, ...],
    [..., 'key' => 6, ...]
];

How do I add elements to the result array only if they aren't in there already? I have the following:

$a = [];
// organize the array
foreach ($array as $k => $v) {
    foreach ($v as $key => $value) {
        if ($key == 'key') {
            $a[] = $value;
        }
    }
}
print_r($a);

Output:

Array
(
  [0] => 1
  [1] => 2
  [2] => 3
  [3] => 1
  [4] => 2
  [5] => 3
  [6] => 4
  [7] => 5
  [8] => 6
)

Instead, I want $a to consist of the unique values. (I know I can use array_unique() after looping to get the desired results, but I just want to know of any other ways.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

神也荒唐 2024-11-15 21:03:14

您应该使用 PHP 函数 in_array (请参阅 http:// /php.net/manual/en/function.in-array.php)。

if (!in_array($value, $array))
{
    $array[] = $value; 
}

这是文档中关于 in_array 的内容:

如果在数组中找到needle,则返回TRUE,否则返回FALSE

You should use the PHP function in_array (see http://php.net/manual/en/function.in-array.php).

if (!in_array($value, $array))
{
    $array[] = $value; 
}

This is what the documentation says about in_array:

Returns TRUE if needle is found in the array, FALSE otherwise.

九局 2024-11-15 21:03:14

您必须对照 in_array 检查每个值:

$a=array();
// organize the array by cusip
foreach($array as $k=>$v){
    foreach($v as $key=>$value){
        if(!in_array($value, $a)){
        $a[]=$value;
        }
    }
}

You'd have to check each value against in_array:

$a=array();
// organize the array by cusip
foreach($array as $k=>$v){
    foreach($v as $key=>$value){
        if(!in_array($value, $a)){
        $a[]=$value;
        }
    }
}
ゃ人海孤独症 2024-11-15 21:03:14

由于您似乎只有 标量值 PHP 的数组更像是一个哈希映射,因此您可以使用value 作为键以避免重复并将 $k 键关联到它们以便能够获取原始值:

$keys = array();
foreach ($array as $k => $v){
    if (isset($v['key'])) {
        $keys[$value] = $k;
    }
}

然后您只需迭代它即可获取原始值:

$unique = array();
foreach ($keys as $key) {
    $unique[] = $array[$key]['key'];
}

这可能不是最明显的也是最全面的方法,但它非常高效,因为它的时间复杂度为 O(n)。

像其他人建议的那样使用 in_array 可能更直观。但是您最终会得到 O(n2) 的算法(in_array 的时间复杂度为 O(n) ) 不适用。即使推送数组中的所有值并使用 array_unique 也会比 in_arrayarray_unique 对 O(n·log n) 中的值进行排序,然后删除连续的重复项)。

Since you seem to only have scalar values an PHP’s array is rather a hash map, you could use the value as key to avoid duplicates and associate the $k keys to them to be able to get the original values:

$keys = array();
foreach ($array as $k => $v){
    if (isset($v['key'])) {
        $keys[$value] = $k;
    }
}

Then you just need to iterate it to get the original values:

$unique = array();
foreach ($keys as $key) {
    $unique[] = $array[$key]['key'];
}

This is probably not the most obvious and most comprehensive approach but it is very efficient as it is in O(n).

Using in_array instead like others suggested is probably more intuitive. But you would end up with an algorithm in O(n2) (in_array is in O(n)) that is not applicable. Even pushing all values in the array and using array_unique on it would be better than in_array (array_unique sorts the values in O(n·log n) and then removes successive duplicates).

忘羡 2024-11-15 21:03:14
if (!in_array(...))  
  array_push(..)
if (!in_array(...))  
  array_push(..)
擦肩而过的背影 2024-11-15 21:03:14

易于编写,但不是最有效的:

$array = array_unique(array_merge($array, $array_to_append));

这个可能更快:

$array = array_merge($array, array_diff($array_to_append, $array));

Easy to write, but not the most effective one:

$array = array_unique(array_merge($array, $array_to_append));

This one is probably faster:

$array = array_merge($array, array_diff($array_to_append, $array));
留蓝 2024-11-15 21:03:14
if (!in_array($value, $a))
  $a[]=$value;
if (!in_array($value, $a))
  $a[]=$value;
生活了然无味 2024-11-15 21:03:14

尝试添加为键而不是值:

添加条目

function addEntry($entry) {
    $this->entries[$entry] = true;
}

获取所有条目

function getEntries() {
    return array_keys($this->enties);
}

Try adding as key instead of value:

Adding an entry

function addEntry($entry) {
    $this->entries[$entry] = true;
}

Getting all entries

function getEntries() {
    return array_keys($this->enties);
}
素罗衫 2024-11-15 21:03:14

如果您可以在代码中使用简写(而不是像某些编码标准推荐的那样编写明确的if块),您可以进一步用这句话简化Marius Schulz的答案

in_array ($value, $array) || $array [] = $value;

If you're okay with using shorthands in your code (instead of writing explicit if blocks, like some coding standards recommend), you can further simplify Marius Schulz's answer with this one-liner:

in_array ($value, $array) || $array [] = $value;
呢古 2024-11-15 21:03:14

如果您不关心键的顺序,可以执行以下操作:

$array = YOUR_ARRAY
$unique = array();
foreach ($array as $a) {
    $unique[$a] = $a;
}

If you don't care about the ordering of the keys, you could do the following:

$array = YOUR_ARRAY
$unique = array();
foreach ($array as $a) {
    $unique[$a] = $a;
}
三生路 2024-11-15 21:03:14

由于有很多方法可以实现所需的结果,并且很多人提供了 !in_array() 作为答案,并且 OP 已经提到了 array_unique 的使用,我我想提供几个替代方案。

使用 array_diff (php >= 4.0.1 || 5) 您可以仅过滤掉不存在的新数组值。或者,您也可以使用 array_diff_assoc 来比较键和值。 http://php.net/manual/en/function.array-diff.php

$currentValues = array(1, 2);
$newValues = array(1, 3, 1, 4, 2);
var_dump(array_diff($newValues, $currentValues));

结果:

Array
(
    [1] => 3
    [3] => 4
)

http://ideone.com/SWO3D1

另一种方法是使用 array_flip 将值分配为键并使用 isset 进行比较,对于大型数据集,这将比 in_array 执行得更快。同样,这仅过滤掉当前值中尚不存在的新值。

$currentValues = [1, 2];
$newValues = [1, 3, 1, 4, 2];
$a = array();
$checkValues = array_flip($currentValues);
foreach ($newValues as $v) {
    if (!isset($checkValues[$v])) {
        $a[] = $v;
    }
}

结果:

Array
(
    [0] => 3
    [1] => 4
)

http://ideone.com/cyRyzN

无论使用哪种方法,您都可以使用 array_merge 将唯一的新值附加到当前值。

  1. http://ideone.com/JCakmR
  2. http://ideone.com/bwTz2u

结果:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Since there are a ton of ways to accomplish the desired results and so many people provided !in_array() as an answer, and the OP already mentions the use of array_unique, I would like to provide a couple alternatives.

Using array_diff (php >= 4.0.1 || 5) you can filter out only the new array values that don't exist. Alternatively you can also compare the keys and values with array_diff_assoc. http://php.net/manual/en/function.array-diff.php

$currentValues = array(1, 2);
$newValues = array(1, 3, 1, 4, 2);
var_dump(array_diff($newValues, $currentValues));

Result:

Array
(
    [1] => 3
    [3] => 4
)

http://ideone.com/SWO3D1

Another method is using array_flip to assign the values as keys and compare them using isset, which will perform much faster than in_array with large datasets. Again this filters out just the new values that do not already exist in the current values.

$currentValues = [1, 2];
$newValues = [1, 3, 1, 4, 2];
$a = array();
$checkValues = array_flip($currentValues);
foreach ($newValues as $v) {
    if (!isset($checkValues[$v])) {
        $a[] = $v;
    }
}

Result:

Array
(
    [0] => 3
    [1] => 4
)

http://ideone.com/cyRyzN

With either method you can then use array_merge to append the unique new values to your current values.

  1. http://ideone.com/JCakmR
  2. http://ideone.com/bwTz2u

Result:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
单挑你×的.吻 2024-11-15 21:03:14

您可以尝试使用“in_array”:

function insert_value($value, &$_arr) {
    if (!in_array($value, $_arr)) {
        $_arr[] = $value;
    }
}

you can try using "in_array":

function insert_value($value, &$_arr) {
    if (!in_array($value, $_arr)) {
        $_arr[] = $value;
    }
}
旧情勿念 2024-11-15 21:03:14

采用 Gumbo 的想法,使代码正常工作:

$array = array('111111','222222','3333333','4444','5555', 
'AAAAAA', 'BBBBBB', 'CCC', 'DDDDDDD', 'EEEEEEEE', 'FFFFFF', 'GGG',
'AAAAAA', 'BBBBBB', 'CCC', 'DDDDDDD', 'EEEEEEEE', 'FFFFFF', 'GGG',
'222222', 
'666666', '777777', 'HHHH');

print_r($array);

$keys= array();
foreach ($array as $k => $v){
    if (isset($v['value'])) {
        $keys[$v] = $k;
    }
}
$unique = array();
foreach ($keys as $key) {
    $unique[] = $array[$key];
}
print "<br><br>";
print_r($unique);

给出:

Array
(
    [0] => 111111
    [1] => 222222
    [2] => 3333333
    [3] => 4444
    [4] => 5555
    [5] => AAAAAA
    [6] => BBBBBB
    [7] => CCC
    [8] => DDDDDDD
    [9] => EEEEEEEE
    [10] => FFFFFF
    [11] => GGG
    [12] => AAAAAA
    [13] => BBBBBB
    [14] => CCC
    [15] => DDDDDDD
    [16] => EEEEEEEE
    [17] => FFFFFF
    [18] => GGG
    [19] => 222222
    [20] => 666666
    [21] => 777777
    [22] => HHHH
)

Array
(
    [0] => 111111
    [1] => 222222
    [2] => 3333333
    [3] => 4444
    [4] => 5555
    [5] => AAAAAA
    [6] => BBBBBB
    [7] => CCC
    [8] => DDDDDDD
    [9] => EEEEEEEE
    [10] => FFFFFF
    [11] => GGG
    [12] => 666666
    [13] => 777777
    [14] => HHHH
)

Taking Gumbo's idea, making the code work:

$array = array('111111','222222','3333333','4444','5555', 
'AAAAAA', 'BBBBBB', 'CCC', 'DDDDDDD', 'EEEEEEEE', 'FFFFFF', 'GGG',
'AAAAAA', 'BBBBBB', 'CCC', 'DDDDDDD', 'EEEEEEEE', 'FFFFFF', 'GGG',
'222222', 
'666666', '777777', 'HHHH');

print_r($array);

$keys= array();
foreach ($array as $k => $v){
    if (isset($v['value'])) {
        $keys[$v] = $k;
    }
}
$unique = array();
foreach ($keys as $key) {
    $unique[] = $array[$key];
}
print "<br><br>";
print_r($unique);

Gives this:

Array
(
    [0] => 111111
    [1] => 222222
    [2] => 3333333
    [3] => 4444
    [4] => 5555
    [5] => AAAAAA
    [6] => BBBBBB
    [7] => CCC
    [8] => DDDDDDD
    [9] => EEEEEEEE
    [10] => FFFFFF
    [11] => GGG
    [12] => AAAAAA
    [13] => BBBBBB
    [14] => CCC
    [15] => DDDDDDD
    [16] => EEEEEEEE
    [17] => FFFFFF
    [18] => GGG
    [19] => 222222
    [20] => 666666
    [21] => 777777
    [22] => HHHH
)

Array
(
    [0] => 111111
    [1] => 222222
    [2] => 3333333
    [3] => 4444
    [4] => 5555
    [5] => AAAAAA
    [6] => BBBBBB
    [7] => CCC
    [8] => DDDDDDD
    [9] => EEEEEEEE
    [10] => FFFFFF
    [11] => GGG
    [12] => 666666
    [13] => 777777
    [14] => HHHH
)
北渚 2024-11-15 21:03:14

使用array_flip(),它可能看起来像这样:

$flipped = array_flip($opts);
$flipped[$newValue] = 1;
$opts = array_keys($flipped);

使用array_unique() - 像这样:

$opts[] = $newValue;
$opts = array_values(array_unique($opts));

注意array_values(...) - 如果您要将数组以 JSON 形式导出到 JavaScript,则需要它。仅 array_unique() 会简单地取消重复键的设置,而无需重建剩余元素。因此,转换为 JSON 后将生成对象,而不是数组。

>>> json_encode(array_unique(['a','b','b','c']))
=> "{"0":"a","1":"b","3":"c"}"

>>> json_encode(array_values(array_unique(['a','b','b','c'])))
=> "["a","b","c"]"

With array_flip() it could look like this:

$flipped = array_flip($opts);
$flipped[$newValue] = 1;
$opts = array_keys($flipped);

With array_unique() - like this:

$opts[] = $newValue;
$opts = array_values(array_unique($opts));

Notice that array_values(...) — you need it if you're exporting array to JavaScript in JSON form. array_unique() alone would simply unset duplicate keys, without rebuilding the remaining elements'. So, after converting to JSON this would produce object, instead of array.

>>> json_encode(array_unique(['a','b','b','c']))
=> "{"0":"a","1":"b","3":"c"}"

>>> json_encode(array_values(array_unique(['a','b','b','c'])))
=> "["a","b","c"]"
骷髅 2024-11-15 21:03:14

要从二维数组中的单列标量值填充唯一值的平面索引数组,您可以使用 array_column() 并将第二个和第三个参数指定为同一所需列。

由于 PHP 不允许数组同一级别上的键重复,因此您将获得所需的唯一值结果。

这种技术是可靠的,因为被隔离的值在用作键时不会被 PHP 改变——对于空值、浮点数、布尔值和更多数据类型来说,情况并非如此。

仅当您想重新索引键时才需要 array_values() ;否则,您可以保留临时键并避免额外的函数调用。

代码:(Demo)

var_export(
    array_values(
        array_column($array, 'key', 'key')
    )
);

输出:

array (
  0 => 1,
  1 => 2,
  2 => 3,
  3 => 4,
  4 => 5,
  5 => 6,
)

为了实现迭代的语言构造,您可以使用无体foreach() 并访问 key 列值两次,以将关联值推入结果数组。 演示

$result = [];
foreach ($array as ['key' => $k, 'key' => $result[$k]]);
var_export(array_values($result));

主题阅读:解构数组时,是否可以多次访问同一个元素值?

To populate a flat, indexed array of unique values from a single column of scalar values from a 2d array, you can use array_column() and nominate the 2nd and 3rd parameters as the same desired column.

Because PHP doesn't allow keys on the same level of an array to be duplicated, you get the desired unique value results.

This technique is reliable because none of the values being isolated will be mutated by PHP upon being used as keys -- this is not true of nulls, floats, booleans, and more data types.

array_values() is only necessary if you want to re-index the keys; otherwise you can leave the temporary keys and avoid the extra function call.

Code: (Demo)

var_export(
    array_values(
        array_column($array, 'key', 'key')
    )
);

Output:

array (
  0 => 1,
  1 => 2,
  2 => 3,
  3 => 4,
  4 => 5,
  5 => 6,
)

For the implementation of a language construct for iteration, you can use a body-less foreach() and access the key column value twice to push associative values into the result array. Demo

$result = [];
foreach ($array as ['key' => $k, 'key' => $result[$k]]);
var_export(array_values($result));

Topical reading: While destructuring an array, can the same element value be accessed more than once?

恋你朝朝暮暮 2024-11-15 21:03:14

您还可以使用 +=

$options1 = []

$options1 += [
      'id' => NULL
    ];

将导致 $options1 等于:

[
  'id' => NULL
];

其中 as

$options2 = ['id' => '121sdd23']

$options2 += [
      'id' => NULL
    ];

将导致 $options2 等于:

[
  'id' => '121sdd23'
];

You can also use +=

$options1 = []

$options1 += [
      'id' => NULL
    ];

will result in $options1 equal to:

[
  'id' => NULL
];

where as

$options2 = ['id' => '121sdd23']

$options2 += [
      'id' => NULL
    ];

will result in $options2 equal to:

[
  'id' => '121sdd23'
];
北城挽邺 2024-11-15 21:03:14

试试这个代码,我从 得到它这里

$input = Array(1,2,3,1,2,3,4,5,6);
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));

Try this code, I got it from here

$input = Array(1,2,3,1,2,3,4,5,6);
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文