0

我想尝试交换这个数组的第一个和最后一个索引:

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

所以它看起来像这样:

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

昨晚我使用这些数组做了类似的事情:

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

我假设这些方法将是相似的。但是,$their_name[0] 返回“J”。

谢谢!

4

2 回答 2

1

这似乎非常基本,但这就是您要问的:

echo $their_name['Jane'];

$their_name['Josh'] = 'son-in-law';
于 2013-01-04T16:47:30.893 回答
1

这是针对您的特定问题的潜在解决方案...

$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"
}
于 2013-01-04T18:34:01.053 回答