3

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...

4

5 に答える 5

3

技術的には、$temp 変数のステップは必要ありません。

$data['entry'] = isset($data['entry'][0]) ? $data['entry'] : array($data['entry']);
于 2013-03-01T04:16:16.370 に答える
2

最もエレガントな方法は、キーが 1 つしかない場合でも、キーに基づいて配列を作成することです。

このような:

$data = Array(
   [date] => 'date'
   [entry] => Array(
      [0] => Array(
         [Title] => 'title0'
         [Price] => 'price0'
      )
   )
 )
于 2013-03-01T02:15:11.947 に答える
0

これは、次の構造体のような多次元配列を定義したためです。

entry = array(array())

2番目のケースでは、宣言しただけですentry = array()

について考える:

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

于 2013-03-01T02:17:28.937 に答える
0
 if(!isset($data['entry']['0'])){
    $temp = $data['entry'];
    unset($data['entry']);
    $data['entry']['0'] = $temp;
 }
 foreach($data['entry'] as $entry) ...

かなり「エレガント」ではありませんが、機能します...

于 2013-03-01T03:13:04.413 に答える