duanji8615 2014-10-15 04:31
浏览 120

如何在foreach循环中使用变量创建多个数组

I want to create a new array for each category each time I iterate through my Categories array. My data comes from a larger array. I want to create a unique array with the name of the appropriate $Categories array value each time I cycle through the outermost foreach. I may not have explained it very well so let me know if there is something I need to elaborate on. Here is a sample of the code (I have simplified it to save space but only omitted key/value pairs where not needed for this example. This is probably not the most efficient way of doing it as I force it to cycle through all the menu items each time it runs for each category, but I will focus on that issue later).

//$menuItems['menu_items']) is the name of the master array from which I am getting all my information

$my_variable_array_name is the array that I wanted to create with a variable so that I can create a new one with a different name each time it runs through the ($Categories as $Category) foreach loop.

$Categories = array('0Cat', '1Cat', '2Cat', '3Cat', '4Cat', '5Cat');
foreach ($Categories as $Category)
{
  foreach($menuItems['menu_items'] as $Curr_Item)
  {
    if($Curr_Item['category']==$Category)
    {    
      $my_variable_array_name[$Category.'_Entry'][$Curr_Item['name']] =
        array('name'=>$Curr_Item['name'],
              'id'=>$Curr_Item['id'],
              'amount'=>$Curr_Item['amount'],
              'on_hold'=>$Curr_Item['on_hold'],
              'category'=>$Curr_Item['category'],
              'Measurement'=>$Curr_Item['Measurement'],);
    }
  }
}

So to sum up and explain it differently, I want to only have to write this chuck one time and each time it runs (for each category entry) it will make an new (different) array with a unique name (a derivative of the category value ie: "1Cat" etc.) So I will end up with 6 different arrays holding the appropriate information.

I tried to use the $Category as the name of the array but it erred out. The code works fine if I give the array a name but it writes it all the the one array, I want each category in a new array.

  • 写回答

2条回答 默认 最新

  • duanqu9292 2014-10-15 04:46
    关注

    Your question sounds really confusing, but I think you are just looking for an iterator that you can use.

    foreach ($categories as $i => $category) {
      // $i starts at 0
    } 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染