【问题标题】:Group array by array name按数组名称对数组进行分组
【发布时间】:2015-08-09 17:14:19
【问题描述】:

我有这个数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Something
            [other_id] => 2
            [other_name] => One
        )

    [1] => Array
        (
            [id] => 1
            [name] => Something
            [other_id] => 3
            [other_name] => Two
        )

    [2] => Array
        (
            [id] => 1
            [name] => Something
            [other_id] => 3
            [other_name] => Three
        )

    [3] => Array
        (
            [id] => 1
            [name] => Something
            [other_id] => 2
            [other_name] => Four
        )

)

现在我需要数组看起来像这样:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Something
            [0] => Array
                (
              [other_id] => 2
                  [other_name] => One
            )       
            [1] => Array
                (
              [other_id] => 3
                  [other_name] => Two
            )       
            [2] => Array
                (
              [other_id] => 4
                  [other_name] => Three
            )       
        )
)

我尝试了不同的方法,但没有结果。我希望有人可以帮助我一点。

【问题讨论】:

  • 向我们展示一些努力。
  • 一些问题:(1)所有id总是一样的吗? (2) 您会考虑使用id 作为数组中的键吗?这将大大简化代码。
  • 不,id 更改。基本上我需要类似的东西:jsfiddle.net/LkjL2584
  • 我接受它,然后你不使用任何特别的键,所以我可以将它们设置为我想要的任何东西。
  • 等等...这对我来说没有意义。在输入中,您有other_id, other_name 组合2, One3, Two3, Three2, Four。在输出中有2, One3, Two4, Three。这里有什么规则?

标签: php arrays


【解决方案1】:

不确定我是否理解您想要的,但这可能会做到:

//Somewhere to store the result.
$output = array();

//Loop through the input array.
foreach($input as $element) {

    $id = $element['id'];
    $other_id = $element['other_id'];

    if(!isset($output[$id])) {
        //ID is not already in the output array, so add it.
        $output[$id] = array(
            'id' => $id,
            'name' => $element['name'],
        );
    }

    if(!isset($output[$id][$other_id])) {
        //Other_ID is not already in the output array, so add it.
        $output[$id][$other_id] = array(
            'other_id' => $other_id,
            'other_name' => $element['other_name'],
        );
    }

}

【讨论】:

  • 这不是正确的循环for($element in $input)
  • Okei,我试过了,但它对我不起作用,因为第一个 other_id 和 other_name 它没有分组。这是 pastebin 网址:pastebin.com/ptnaspHi
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
  • 2012-05-23
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多