doubingling4706 2017-07-16 10:17
浏览 90
已采纳

基于var的PHP填充数组

I feel like I'm struggling to find the answer here because I think I'm missing some key piece of info.

What I am trying to do is run a loop over some data, and then do something different with it based on one of it's values.

So the print_r of the data I am looping over gives me this. This is all good, it has only the data I need, nothing excess.

Array
(
[foodid] => 1
[menuid] => 1789798798
[creatorid] => 1
[foodtype] => hotdog
[frequency] => weekly
[cost] => 20
[chargedate] => 2017-07-14 11:05:18
)

And I want to do SOMETHING to it, depending on the value in frequency. The things I want to do are all stored in a set of identical arrays.

weekly, 2weekly, monthly, daily. eg

$_weekly = array(
"cost" => "2",
"order" => "5",
"years" => "0",
);

$_2weekly = array(
"cost" => "4",
"order" => "10",
"years" => "0",
);

Similar arrays for weekly 2weekly etc.

It seems simple to just use a var like $workingvar in the loop. So when I get there I can just use $workingvar = $_weekly, or $workingvar = $_2weekly.

So, how can I set the contents of $workingvar to be one of those existing arrays? Then I can use the same loop/function on each row in the data, and change the values it pulls in, depending on what that frequency value contains.

Edit added second array example.

  • 写回答

2条回答 默认 最新

  • douwei3172 2017-07-16 10:23
    关注

    So you need variable variable, in your case it is:

    $arr['frequency'] = 'weekly';
    $_weekly = [11,22,33];
    
    $workingvar = ${'_' . $arr['frequency']};
    var_dump($workingvar);
    

    But having array with same keys is a more preferred solution (simply because it's more readable and shorter):

    $arr['frequency'] = 'weekly';
    $arrs = [
        'weekly' => [11,22,33],
    ];
    var_dump($arrs[$arr['frequency']]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器