-2

I have tried this line of code to display an array:

foreach($users_array as $value){    
    echo "<pre>";
    print_r($value);                     
} 

Which display this kind of array.

Array
(
    [auto_id] => 45
    [id] => 20151116
    [name] => Peter 2
    [department] => 
    [position] => 
    [rate] => 300
    [date_added] => 2017-07-26 09:31:44
)
Array
(
    [auto_id] => 80
    [id] => 20160410
    [name] => John 2
    [department] => 
    [position] => 
    [rate] => 400
    [date_added] => 2017-07-26 09:31:48
)

Now what I wanted to do is to make the id of employee to be the key of an array and make them as one multi-dimensional array.

Example output should be like this:

Array
(
    [20151116] => Array
    (
        [auto_id] => 45
        [id] => 20151116
        [name] => Peter 2
        [department] => 
        [position] => 
        [rate] => 300
        [date_added] => 2017-07-26 09:31:44
    )

    [20160410] => Array
    (
        [auto_id] => 80
        [id] => 20160410
        [name] => John 2
        [department] => 
        [position] => 
        [rate] => 400
        [date_added] => 2017-07-26 09:31:48
    )

)

Any help is appreciated. Thank you.

0

3 Answers 3

1

It's probably easiest to make a new array the you output directly, and loop over the existing array, setting the id as an index of the new array:

<?php

$newArray = array();

foreach($users_array as $value) {
    $newArray[$value["id"]] = $value;
    print_r($newArray);
}

Hope this helps! :)

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

2 Comments

Thanks for your help but echoing the array inside the loop won't work.
You could always take it outside of the loop. I was a little unsure of your exact structure, as you don't seem to be outputting a single array currently, but two different arrays (your print_r() is current inside of your loop).
0

Here you need to change

  $final = array();
  foreach($users_array as $value){    
      $final[$value["id"]] = $value;                 
  }
      echo "<pre>";
      print_r($final);  

Comments

0

Use the function array_column() and array_combine(), like this:

$employee_id = array_column($users_array,'id');
$users_array = array_combine($employee_id,$users_array);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.