skip to Main Content

I have an array in my php code


$list = array(
'RETAIL' => 'SUPERMARKET'
'RETAIL' => 'BAR'
'RETAIL' => 'DEP. MARKET'
'BUSINESS' => 'HOTEL'
'BUSINESS' => 'PUB'
'OTHER' => 'GROCERY'
'OTHER' => 'BUTCHERY'
// I have 20+ items
);

foreach( $list as $type => $name ){
  var_dump($type,$name);
}

//var_dump() output 
// RETAIL SUPERMARKET
// BUSINESS HOTEL
// OTHER BUTCHERY

I’m facing the problem that when I try to loop the array only three values will be returned and the rest are ignored. How I can fix this?
I’m trying to loop the array to save the data into a custom wordpress database. With the same way I’ve successfully looped another array inserted the keys and values into the db.

3

Answers


  1. I think a better structure for your array would something like this

    $list = [
        'RETAIL' => [
            'BAR',
            'RESTAURANT'
        ]
    ];
    

    And you could loop over like so

    foreach ($list as $businessType => $businesses) {
        foreach ($businesses as $business) {
             echo "<li>{$business}</li>";
        }
    }
    

    Just an example

    Login or Signup to reply.
  2. As a general way of handling instances where you have more than one element to each piece of data (even when it’s not in a tree structure like this may be), you should structure each item in the list as either an array or object, eg:

    $list_of_arrays = [
        ['RETAIL', 'SUPERMARKET'],
        ['RETAIL', 'BAR'],
        ['RETAIL', 'DEP. MARKET'],
    ];
    
    foreach( $list_of_arrays as $array ){
        echo "<li>{$array[0]} {$array[1]}</li>";
    }
    

    or

    $list_of_objects = [
        (object)['type' => 'RETAIL', 'subtype' => 'SUPERMARKET'],
        (object)['type' => 'RETAIL', 'subtype' => 'BAR'],
        (object)['type' => 'RETAIL', 'subtype' => 'DEP. MARKET'],
    ];
    
    foreach( $list_of_objects as $object ){
        echo "<li>{$object->type} {$object->subtype}</li>";
    }
    
    Login or Signup to reply.
  3. Maybe I show heavily but as you only have two data for each entity, why your table is not built like this at the base…?

    $list = array(
    'SUPERMARKET'=>'RETAIL',
    'BAR'=>'RETAIL',
    'DEP. MARKET'=>'RETAIL',
    'HOTEL'=>'BUSINESS',
    'PUB'=>'BUSINESS',
    'GROCERY'=>'OTHER',
    'BUTCHERY'=>'OTHER'
    // I have 20+ items
    );
    

    You do have keys that uniquely identify entities.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search