用数组替换数组中的一个值

时间:2012-12-18 19:03:06

标签: php

我的数组转换有问题。 我有这个数组:

 Array
  (
   [0] => Array
    (
        [x] => 1291
        [y] => 32
        [z] => 1142
        [number] => 51
    )

   [1] => Array
    (
        [x] => 1415
        [y] => 32
        [z] => 1142
        [number] => 22
    )
)

如何制作数组

 Array
  (
   [51] => Array
    (
        [x] => 1291
        [y] => 32
        [z] => 1142
    )

   [22] => Array
    (
        [x] => 1415
        [y] => 32
        [z] => 1142
    )

)

[数字]不必从数组中删除。重要的是,成为关键。

4 个答案:

答案 0 :(得分:2)

$numbers = array();
//Get the list of 'number' keys and unset them (optional)
foreach ($array as &$values) {
   $numbers[] = $values['number'];
   unset($values['number']);
}
//create a new array with numbers as keys and the original array as values
//You could also overwrite the original array, which will save some memory
$result = array_combine($numbers, $array);

答案 1 :(得分:1)

您可以创建新阵列

$newarray = array();
foreach($yourarray as $k=>$v) {
    $newarray[$v['number']] = $v
}

print_r($newarray);

答案 2 :(得分:1)

对原始数组进行简单循环可以解决这个问题:

$new = array();

foreach($old as $item) {
    $key = $item['number'];
    $new[$key] = $item;
}

var_dump($new);

答案 3 :(得分:1)

无需像许多其他答案所示创建新阵列,这可以就地完成。

foreach ($array as $key => $value)
{
    $array[$value["number"]] = $array[$key];

    // remove number attribute (optional)
    unset($array[$value["number"]]["number"]);

    // remove array @ original key
    unset($array[$key]);
}