douzongluo7542 2013-01-04 16:34
浏览 59
已采纳

针对关联(一维)数组的特定部分?

I want to try to swap the first and last index's of this array:

 <?php
 $their_name = array(
      'Jim'   => 'dad', 
      'Josh'  => 'son', 
      'Jamie' => 'mom', 
      'Jane'  => 'daughter', 
      'Jill'  => 'daughter'
 );
 ?>

So that it will look like this:

 <?php
 $their_name = array(
      'Jill'   => 'dad', 
      'Josh'  => 'son', 
      'Jamie' => 'mom', 
      'Jane'  => 'daughter', 
      'Jim'  => 'daughter'
 );
 ?>

I did something similar last night with an array using these:

$temp                   = $user_name[0];     
$user_name[0]           = end($user_name);    
$count                  = count($user_name);  
$user_name[$count-1]    = $temp;             
return $user_name;                            

I'm assuming that these methodology will be similar. However, $their_name[0] returns 'J'.

Thanks!

  • 写回答

2条回答 默认 最新

  • duanaigua4033 2013-01-04 18:34
    关注

    Here's a potential solution to your specific problem...

    $their_name = array(
      'Jim'   => 'dad', 
      'Josh'  => 'son', 
      'Jamie' => 'mom', 
      'Jane'  => 'daughter', 
      'Jill'  => 'daughter'
    );
    // rewind array pointer to first element
    reset($their_name);
    // get key name
    $firstKey = key($their_name);
    // get value and remove from array
    $firstValue = array_shift($their_name);
    
    // advance pointer to last element 
    end($their_name);
    // get key name
    $lastKey = key($their_name);
    // get value and remove from array
    $lastValue = array_pop($their_name);
    
    // first element using last key and first value
    $firstElement = array($lastKey => $firstValue);
    // last element using first key and last value
    $lastElement = array($firstKey => $lastValue);
    
    // add them to the remaining elements 
    $their_name = $firstElement + $their_name + $lastElement;
    
    var_dump($their_name);
    // Result:
    array(5) {
        ["Jill"]=>
        string(3) "dad"
        ["Josh"]=>
        string(3) "son"
        ["Jamie"]=>
        string(3) "mom"
        ["Jane"]=>
        string(8) "daughter"
        ["Jim"]=>
        string(8) "daughter"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错