Alltheprettyhorses
Alltheprettyhorses

Reputation: 133

PHP Foreach loop with a single element

I have a function that parses the 'entry's in a nested array:

$data = Array(
   [date] => 'date'
   [entry] => Array(
      [0] => Array(
         [Title] => 'title0'
         [Price] => 'price0'
      )
      [1] => Array(
         [Title] => 'title1'
         [Price] => 'price1'
      )
   )
 )

Looping through this with a foreach($data['entry'] as $entry){ works great if there is more than one entry. However, it there is only one entry I am served:

 $data = Array(
   [date] => 'date'
   [entry] => Array(
      [Title] => 'title'
      [Price] => 'price'
   )
 )

And the foreach loop fails.

Is there an elegant way to write a foreach that will grab each entry[0], entry[1] sub array (like normal) or back off one level if there is only one entry and grab the entire 'entry' array instead?


Addendum: the stuff I'm doing on the entries is pretty involved... I supposed I could separate that out into a different function, do an if(is_array) check then call the function once, or for each... but that seems inelegant...

Upvotes: 3

Views: 11972

Answers (5)

andymo
andymo

Reputation: 87

try this it work for me

foreach ($data as $key => $value) {
            if (!is_numeric($key)) {
            //not multidimensional
                 $data1 = $data;                    
            } else {                   
                 $data1 = $value;
            }
            //do your stuff
            echo $data1;                        
}

eventualy you can make a recursive function

Upvotes: 0

user1753144
user1753144

Reputation: 1

This is because you defined a multi-dimensional array like this struct:

entry = array(array())

in 2nd case you only declared entry = array()

think about:

if(is_array(entry[0])) ...

Upvotes: 0

Michael L.
Michael L.

Reputation: 618

Technically, you don't need the $temp variable step.

$data['entry'] = isset($data['entry'][0]) ? $data['entry'] : array($data['entry']);

Upvotes: 3

Alltheprettyhorses
Alltheprettyhorses

Reputation: 133

 if(!isset($data['entry']['0'])){
    $temp = $data['entry'];
    unset($data['entry']);
    $data['entry']['0'] = $temp;
 }
 foreach($data['entry'] as $entry) ...

Not quite "elegant" but it works...

Upvotes: 0

user1765062
user1765062

Reputation:

The best elegant way is to create an array based on keys even if there is just one.

Like this:

$data = Array(
   [date] => 'date'
   [entry] => Array(
      [0] => Array(
         [Title] => 'title0'
         [Price] => 'price0'
      )
   )
 )

Upvotes: 2

Related Questions