douwen3500 2016-12-24 10:12 采纳率: 0%
浏览 36
已采纳

如何在php中使用键存储每个数组值

I want to store my variables in an array alongside their keys like :

filter : [ 
"0" : "test",
"1" : "you",
"2" : "php"
]

I have filter[] array in the first place and each time with update request I want to add a value to this array with it's key, automate created key.

I've tried this two methods but they are not storing variable keys:

//$seat_filters = filter array fetched from db

$filters = array($request->input('filter'));

$filters_array = array_merge($seat_filters, $filters);

When I check the result of $filters_array I get :

filter : [
"test",
"you",
"php"
]

Same thing happens in below method of storing values in array :

 array_push($seat_filters ,$request->input('filter'));

Only second method is shorter. FYI : This results are in JSON format.

  • 写回答

3条回答 默认 最新

  • dongxun6458 2016-12-24 10:34
    关注

    Though I don't understand what all these for, but still some advices.

    So you have an array like:

    $a = ["test","you","php"];
    // though it's indexes are not visible - they exist
    $filter = [];
    // you can see indexes in this `foreach`
    foreach ($a as $k => $v) {
        echo 'Key is ', $k, '; value is ', $v;
        // now you can add both values to your filter
        $filter[] = [$k, $v];
    }
    print_r($filter);
    echo json_encode($filter); // [[0,"test"],[1,"you"],[2,"php"]]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线