phparraysmultidimensional-array

Create an associative 2d array from a flat array of keys and a static associative array


I need to create a 2d array using one array's values as keys as well as a new column value, and each row should have several associative elements provided by another flat associative array.

stores_array:

Array
(
    [0] => store1
    [1] =>store2
)  

items_array:

Array  
(  
  [electronics]=>led tv  
  [cosmetics]=>eyeliner  
  [fruits]=>apple 
  [vegetables]=>cabbage  
)  

Here is what I have so far:

$new_array = array();
foreach($stores_array as $t) {
    $new_array[$t] = $items_array;
}
  
echo '<pre>';
    print_r($new_array);  
echo '<pre/>';  

Here is the current output:

Array
(
[store1] => Array
    (
      [electronics]=>led tv  
      [cosmetics]=>eyeliner  
      [fruits]=>apple 
      [vegetables]=>cabbage  
    )  
[store2] => Array
    (
      [electronics]=>led tv  
      [cosmetics]=>eyeliner  
      [fruits]=>apple 
      [vegetables]=>cabbage  
    )
)  

What I want to achieve is to add some other values in each of the array rows. See the arrows regarding what/where I intend to add data.

Array
(
[store1] => Array
    (
      [electronics]=>led tv  
      [cosmetics]=>eyeliner  
      [fruits]=>apple 
      [vegetables]=>cabbage
      [store]=>store1  <------- how can I add these?
    )  
[store2] => Array
    (
      [electronics]=>led tv  
      [cosmetics]=>eyeliner  
      [fruits]=>apple 
      [vegetables]=>cabbage 
      [store]=>store2  <------- how can I add these?
    )
)  

Solution

  • Try this:

    $new_array = array();
    foreach($stores_array as $t) {
        $new_array[$t] = $items_array;
        $new_array[$t]["store"]=$t;
    }
    
    echo '<pre>';
    print_r($new_array);  
    echo '<pre/>';