简体   繁体   中英

turn 2d array into 1d PHP

I have an array (sample below) containing 3 arrays with very similar content. I was wondering if there was an easy way to put everything into one array, rather than 3 separate ones. Everything I try seems to just overwrite the data and I'm left with the info from the 3rd array only.

array
  0 => 
    array
      'america' => int 19
      'music' => int 6
      'states' => int 5
      'bank' => int 5
  1 => 
    array
      'america' => int 19
      'home' => int 3
      'society' => int 2
      'writers' => int 2
   2 => 
    array
      'america' => int 19
      'lutheran' => int 4
      'church' => int 4
      'national' => int 4
      'cruises' => int 3

Ideally the end result will look like this:

array
          'america' => int 19
          'music' => int 6
          'states' => int 5
          'bank' => int 5
          'america' => int 19
          'home' => int 3
          'society' => int 2
          'writers' => int 2
          'america' => int 19
          'lutheran' => int 4
          'church' => int 4
          'national' => int 4
          'cruises' => int 3

Any solutions? thanks

You won't be able to have an associative array with the same key values (ie 3 keys of "America", etc.). When you try to set those keys in the array, you will simply overwrite the previous value.

I was wondering if there was an easy way to put everything into one array

Short answer is no.

You could make a class with a variable for the original int and a value for the number of times it occurs and then have the array point to objects of the class. Same idea could be implemented using a linked list, though both ways are more complex than what you already have.

For example the key 'america' would point to an object with one variable set to 19 and the other variable set to 3.

Question: do you need to know which of the original arrays a value comes from? If yes then what I mentioned above would loose that property.

function array_2d_to_1d($array)
                                    {
                                        $my_val=array();
                                        $my_key=array();
                                        foreach ($array as $value) {
                                             array_push($my_val, $value['cat_title']);
                                             array_push($my_key, $value['cat_id']);
                                         }

                                        $result = array_combine($my_key, $my_val);
                                        return $result;

                                    }                                

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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