0

I want to change my array from, how can i make this kind of a change.

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 ) );

to:

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
  • Can you format input and output properly, please? Commented Dec 19, 2017 at 16:17

1 Answer 1

5

You can add elements to an associative array directly:

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

You can also initiate one with keys and values directly:

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

Also keep in mind that not any variable can be used as a key, as stated in the PHP documentation for arrays:

The key can either be an integer or a string. The value can be of any type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.