dstjh46606 2012-08-05 16:30
浏览 78
已采纳

PHP从开始到结束时获取数组键和值

I have a PHP array that has literal_key => value. I need to shift the key and value off the beginning of the array and stick it at the end (keeping the key also).

I've tried:

$f = array_shift($fields);
array_push($fields, $f);

but this loses the key value. Ex:

$fields = array ("hey" => "there", "how are" => "you");

// run above

this yields:

$fields = array ("how are" => "you", "0" => "there");

(I need to keep "hey" and not have 0) any ideas?

  • 写回答

2条回答 默认 最新

  • duanchi3109 2012-08-05 16:43
    关注

    As far as I can tell, you can't add an associative value to an array with array_push(), nor get the key with array_shift(). (same goes for pop/push). A quick hack could be:

    $fields = array( "key0" => "value0", "key1" => "value1");
    //Get the first key
    reset($fields);
    $first_key = key($fields);
    $first_value = $fields[$first_key];
    unset($fields[$first_key]);
    
    $fields[$first_key] = $first_value;
    

    See it work here. Some source code taken from https://stackoverflow.com/a/1028677/1216976

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面