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

问题描述 投票:0回答:1

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

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)) */ 
}
php arrays associative-array
1个回答
5
投票

您可以直接向关联数组添加元素:

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

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

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

还要记住,没有任何变量可以用作密钥,如PHP documentation for arrays中所述:

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

© www.soinside.com 2019 - 2024. All rights reserved.