繁体   English   中英

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

[英]How to change the array structure of associative array in Php

我想更改阵列,我该如何进行更改。

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)) */ 
}

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

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

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

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

还请记住,如数组PHP文档中所述,不能将任何变量用作键:

键可以是整数或字符串。 该值可以是任何类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM