1

我需要弄清楚什么 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 中做到这一点?

先感谢您。

4

5 回答 5

7

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

于 2013-11-06T23:21:18.950 回答
4

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

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

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

于 2013-01-18T12:59:55.310 回答
1
 $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;
 }
于 2013-01-18T13:01:04.803 回答
1

您必须手动执行此操作:

$input  = array( /* your data */ );
$output = array();

foreach ( $input as $values ) {
  $output[ $values['index'] ] = $values;
}
于 2013-01-18T13:01:09.910 回答
1
public static function normArray($key, $inputArray)
{
    $outputArray = array();
    foreach ($inputArray as $item) {
        $index = intval($item[$key]);
        $outputArray[$index] = $item;
    }
    return $outputArray;
}
于 2014-02-26T23:49:49.763 回答