拆分阵列

时间:2012-11-27 18:14:06

标签: php arrays

我有一个对象数组。

我需要的是将每个对象的[name]放入另一个数组中,但我不想重复。

我该怎么做?

Array (
    [0] => ADOFetchObj Object
        (
            [name] => Team 1
            [att] => None
            [idGrupo] => 1
            [idModulo] => 4
            [ler] => 1
            [escrever] => 1
            [excluir] => 1
        )

    [1] => ADOFetchObj Object
        (
            [name] => Team 1
            [nomeModulo] => Aplicar Juros
            [idGrupo] => 1
            [idModulo] => 1006
            [ler] => 1
            [escrever] => 1
            [excluir] => 1
        )

    [2] => ADOFetchObj Object
        (
            [name] => Team 2
            [att] => None
            [idGrupo] => 1
            [idModulo] => 10
            [ler] => 1
            [escrever] => 1
            [excluir] => 1
        )

    [3] => ADOFetchObj Object
        (
            [name] => Team 2
            [att] => None
            [idGrupo] => 1
            [idModulo] => 1012
            [ler] => 1
            [escrever] => 1
            [excluir] => 1
        )
)

谢谢!

5 个答案:

答案 0 :(得分:5)

你可以这样做:

$names = array();
foreach($arr as $list) {
    $names[$list->name] = true; // can be *any* arbitrary value
}
$names = array_keys($names);

这将起作用,因为根据定义,数组键必须是唯一的。

答案 1 :(得分:3)

array_unique(array_map(function($element) {
    return $element->name;
}, $my_array));

答案 2 :(得分:3)

你去了

$res = array();

foreach($arr as $var)
{
    if(!in_array($var->name, $res))
    {
      $res[] = $var->name;
    }
}

答案 3 :(得分:2)

首先,将名称复制到新数组:

$arrNames = array();

foreach($arrOriginal as $objObject) {
    array_push(
        $arrNames,
        $objObject->name
    );
}

然后删除重复的名称:

$arrNames = array_unique($arrNames);

答案 4 :(得分:0)

$n = array();

foreach($array as $d) $n[] = $d->name;

$n = array_unique($n);