如何在Php中改变关联数组的数组结构

时间:2017-12-19 16:15:57

标签: php arrays associative-array

我想改变我的阵列,我怎样才能做出这种改变。

Array ( [0] => 53720 [1] => Array( ['Build Quality'] => 1=>10, 2=>9, 3=>7 ['Versatality'] => 1=>9, 2=>8, 3=>7 ['value'] => 1=>8, 2=>6, 3=>5 ) );

到:

Array ( 53720 =>['Build Quality' => [1=>10, 2=>9, 3=>7], 'Versatality' => [1=>9, 2=>8, 3=>7], 'value' => [1=>8, 2=>6, 3=>5] ] );

function get_array(){

  $factor = array([0] => 'Build Quality' [1] => 'Versatality' [2] => 'Value');  
  $rank = array([0] => 1=>10,2=>9,3=>7 [1] => 1=>9,2=>8,3=>7 [2] => 1=>8,2=>6,3=>5);  
  $assoc_array = array_combine($factor, $rank);
  $post_id = get_current_post_id(); //gives 53720   
  $result = array();
  array_push($result, $post_id, $assoc_array);  
  print_r($result);  
  return $result[$post_id];

/* output: Array ([0] => 53720 [1] => Array (['Build Quality'] => 1=>10,2=>9,3=>7 ['Versatality'] => 1=>9,2=>8,3=>7 ['Value'] => 1=>8,2=>6,3=>5)) */ 
}

1 个答案:

答案 0 :(得分:5)

您可以直接将元素添加到关联数组中:

$result = [];
$result[$post_id] = $assoc_array;

您也可以直接使用键和值启动一个:

$result = [
    $post_id => $assoc_array
];

另请注意,并非任何变量都可用作关键字,如PHP documentation for arrays中所述:

  

密钥可以是整数或字符串。值可以是任何类型。