如何清理数组并设置新密钥?

时间:2014-05-06 03:41:07

标签: php arrays

我有一个多阵列:

array(2) {
    ["clean_bin_number"]=>
    array(1) {
      [0]=>
      array(1) {
        [0]=>
        string(7) "1004077"
      }
    }
    ["a_values"]=>
    array(6) {
      [0]=> "14"
      [1]=> "1"
      [2]=> "43"
      [3]=> "7"
      [4]=> "11"
      [5]=> "2"
    }

它变得更加混乱,但我设法将它清理到这一点。 现在我正在尝试实现一个看起来像这样的数组,但我找不到......

array(2) {
        ["clean_bin_number"] => "1004077"
        }
        ["a_values"]=>
        array(6) {
          "Total A" => "14"
          "Open A" => "1"
          "Total B" => "43"
          "Open B" => "7"
          "Total C" => "11"
          "Open C" => "2"
        }

a_values数组的顺序始终保持不变,但我仍无法设置其键....

谢谢

2 个答案:

答案 0 :(得分:0)

当你有一个标准的结构时,这应该可以解决问题。

$reference_array //Your reference array

//Assign to new array
$my_new_array['clean_bin_number'] =  $reference_array['clean_bin_number'][0][0];
$my_new_array['a_values']['Total A'] = $reference_array['a_values'][0];
$my_new_array['a_values']['Open A'] = $reference_array['a_values'][1];
$my_new_array['a_values']['Total B'] = $reference_array['a_values'][2];
$my_new_array['a_values']['Open B'] = $reference_array['a_values'][3];
$my_new_array['a_values']['Total C'] = $reference_array['a_values'][4];
$my_new_array['a_values']['Open C'] = $reference_array['a_values'][5];

答案 1 :(得分:0)

或者,你可以这样做。考虑这个例子:

$data = array(
    'clean_bin_number' => array(
        0 => array(0 => ('1004077')),
    ),
    'a_values' => array(
        0 => '14',
        1 => '1',
        2 => '43',
        3 => '7',
        4 => '11',
        5 => '2',
    ),
);

// if this is supposed to be fixed leveled, try to access it directly.
$new_data['clean_bin_number'] = $data['clean_bin_number'][0][0];

// first get them by two's
$a_values = array_chunk($data['a_values'], 2);
$initial = 'A'; // first letter

// assign each two, then increment the letter
foreach($a_values as $key => $value) {
    $new_data['a_values']["Total $initial"] = $value[0];
    $new_data['a_values']["Open $initial"] = $value[1];
    $initial++;
}


print_r($new_data);

示例输出:

Array
(
    [clean_bin_number] => 1004077
    [a_values] => Array
    (
        [Total A] => 14
        [Open A] => 1
        [Total B] => 43
        [Open B] => 7
        [Total C] => 11
        [Open C] => 2
    )

)