如何更改php数组中的键值

时间:2011-11-08 14:50:04

标签: php arrays multidimensional-array

  

可能重复:
  Changing a nested (multidimentional) array into key => value pairs in PHP

我有这个数组

[5] => Array
        (
            [completed_system_products_id] => 1
            [completed_systems_id] => 76
            [step_number] => 1
            [product_id] => 92
            [category] => hardware
            [date_added] => 2011-05-03 13:44:01
        )

    [4] => Array
        (
            [completed_system_products_id] => 2
            [completed_systems_id] => 76
            [step_number] => 2
            [product_id] => 62
            [category] => hardware
            [date_added] => 2011-05-03 13:44:51
        )

    [3] => Array
        (
            [completed_system_products_id] => 3
            [completed_systems_id] => 76
            [step_number] => 3
            [product_id] => 104
            [category] => hardware
            [date_added] => 2011-05-03 13:44:56
        )

    [2] => Array
        (
            [completed_system_products_id] => 4
            [completed_systems_id] => 76
            [step_number] => 4
            [product_id] => 251
            [category] => hardware
            [date_added] => 2011-05-03 13:48:56
        )

如何使键值与[step_number] =>

相同

所以例如我想要这个结果

    [1] => Array
        (
            [completed_system_products_id] => 1
            [completed_systems_id] => 76
            [step_number] => 1
            [product_id] => 92
            [category] => hardware
            [date_added] => 2011-05-03 13:44:01
        )

    [2] => Array
        (
            [completed_system_products_id] => 2
            [completed_systems_id] => 76
            [step_number] => 2
            [product_id] => 62
            [category] => hardware
            [date_added] => 2011-05-03 13:44:51
        )

    [3] => Array
        (
            [completed_system_products_id] => 3
            [completed_systems_id] => 76
            [step_number] => 3
            [product_id] => 104
            [category] => hardware
            [date_added] => 2011-05-03 13:44:56
        )

    [4] => Array
        (
            [completed_system_products_id] => 4
            [completed_systems_id] => 76
            [step_number] => 4
            [product_id] => 251
            [category] => hardware
            [date_added] => 2011-05-03 13:48:56
        )

3 个答案:

答案 0 :(得分:1)

$new = array();
foreach ($old as $value) {
    $new[$value['step_number']] = $value;
}
$old = $new;

答案 1 :(得分:0)

$result = array(); // Create a new array to hold the result
foreach ($array as $val) { // Loop the original array
  $result[$val['step_number']] = $val; // Add the value to the new array with the correct key
}
ksort($result); // Sort the array by key
print_r($result); // Display the result

答案 2 :(得分:0)

$results = array();
foreach ($array as $item)
{
  $results[$item['step_number']] = $item;
}