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

时间:2013-01-04 16:34:57

标签: php arrays indexing key associative

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

 <?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'。

谢谢!

2 个答案:

答案 0 :(得分:1)

看起来非常基本,但这就是你要问的问题:

echo $their_name['Jane'];

$their_name['Josh'] = 'son-in-law';

答案 1 :(得分: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"
}