【问题标题】:How do I move array child value to parent key?如何将数组子值移动到父键?
【发布时间】:2013-01-18 12:52:36
【问题描述】:

我需要弄清楚什么 PHP 函数可以实现我的目标。

这是我拥有的一个 PHP 数组:

Array
(
[0] => Array
    (
        [id] => 6
        [index] => 1
        [active] => 1
        [name] => MyName
    )

[1] => Array
    (
        [id] => 1
        [index] => 2
        [active] => 1
        [name] => YourName
    )

[2] => Array
    (
        [id] => 2
        [index] => 4
        [active] => 1
        [name] => TheirName
    )
}

我想获取“索引”值并使其成为该数组父级的 KEY,因此该数组将变为:

Array
(
[1] => Array
    (
        [id] => 6
        [index] => 1
        [active] => 1
        [name] => MyName
    )

[2] => Array
    (
        [id] => 1
        [index] => 2
        [active] => 1
        [name] => YourName
    )

[4] => Array
    (
        [id] => 2
        [index] => 4
        [active] => 1
        [name] => TheirName
    )
}

谁能告诉我如何在 PHP 中做到这一点?

提前谢谢你。

【问题讨论】:

  • 感谢三位的帮助。我不确定将谁指定为正确答案,所以我只选择了获得第一票的那个。但是你们都对此非常有帮助!再次感谢您。

标签: php arrays array-splice


【解决方案1】:

你可以使用:array_column($array, null, 'index'); 是更好的解决方案,但仅适用于 >= 5.5 php 版本

【讨论】:

  • 很好的解决方案,就一行!
  • 这是我见过的最好的解决方案。所有其他解决方案都会创建一个新数组,而不是更改现有数组。
  • 天啊!!在你尝试这个并看到魔法之前,你不会知道它。这应该是公认的答案。
【解决方案2】:

不是最优雅的解决方案,但它可以工作(它实际上并不移动数组,它只是生成一个符合您要求的新数组):

$resultArr = array();
foreach ($mainArr as $value) {
    $resultArr[$value['index']] = $value;
}
unset($mainArr); // or $mainArr = $resultArr;

这样您就不会覆盖原始数组中的任何现有键。

【讨论】:

    【解决方案3】:
     $a =  array
     (
        0 => array
        (
            "id" => 6,
            "index" => 1,
            "active" => 1,
            "name" => "MyName"
            ),
    
        1 => Array
        (
            "id" => 1,
            "index" => 2,
            "active" => 1,
            "name" => "YourName"
            ),
    
        2 => Array
        (
            "id" => 2,
            "index" => 4,
            "active" => 1,
            "name" => "TheirName"
            )
    );
    
     $newArray = array();
     foreach ($a as $foo) {
        $newArray[$foo['index']] = $foo;
     }
    

    【讨论】:

      【解决方案4】:

      您必须手动完成:

      $input  = array( /* your data */ );
      $output = array();
      
      foreach ( $input as $values ) {
        $output[ $values['index'] ] = $values;
      }
      

      【讨论】:

        【解决方案5】:
        public static function normArray($key, $inputArray)
        {
            $outputArray = array();
            foreach ($inputArray as $item) {
                $index = intval($item[$key]);
                $outputArray[$index] = $item;
            }
            return $outputArray;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-05-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-08
          • 2019-09-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多