Home > Enterprise >  PHP - foreach loop not return all keys and values
PHP - foreach loop not return all keys and values

Time:10-15

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.

CodePudding user response:

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

CodePudding user response:

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>";
}

CodePudding user response:

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.

  • Related