我有一个形式的关联数组:
$input = array("one" => <class object1>,
"two" => <class object2,
... //and so on);
$ input的键保证是唯一的。我还有一个名为moveToHead($key)
的方法,它将$input[$key]
元素移动到此关联数组的第0个位置。我几乎没有问题:
$key => $value
对的数组条目移动到索引0并保留$key
原样?我正在考虑为第二点(一个子解决方案)做array_flip,但后来发现array_flip
只能在数组元素为int和string时才能完成。有什么指针吗?
答案 0 :(得分:1)
关联数组的“索引”是关键。在数字索引数组中,“键”是索引号。
编辑:我收回了它。 PHP的关联数组是有序的(如其他语言中的Ordered Maps)。
但也许你真正想要的是一个有序的关联数组?
$input = array(array("one" => <class object1>),
array("two" => <class object2>)
//...
);
答案 1 :(得分:1)
使用名为array_keys
的函数,您可以确定键的索引:
$keys = array_flip(array_keys($input));
printf("Index of '%s' is: %d\n", $key, $keys[$key]);
要在某个位置插入数组(例如在开头),有array_splice
函数。因此,您可以创建要插入的数组,从旧位置删除值并将其拼接在:
$key = 'two';
$value = $input[$key];
unset($input[$key]);
array_splice($input, 0, 0, array($key => $value));
array union operator可能有类似的东西,但仅仅是因为你想要移到顶端:
$key = 'two';
$value = $input[$key];
unset($input[$key]);
$result = array($key => $value) + $input;
但我认为这可能比array_splice
有更多的开销。
答案 2 :(得分:1)
以下是我提出的建议:
$arr = array('one' => 'Value1', 'two' => 'Value2', 'three' => 'Value3');
function moveToHead($array,$key) {
$return = $array;
$add_val = array($key => $return[$key]);
unset($return[$key]);
return $add_val + $return;
}
print_r(moveToHead($arr,'two'));
结果
Array
(
[two] => Value2
[one] => Value1
[three] => Value3
)
答案 3 :(得分:0)
您可以使用内部数组指针功能来执行您想要的操作:
$input = array(
"one" => "element one",
"two" => "element two",
"three" => "element three",
);
reset($input); // Move to first element.
echo key($input); // "one"
您可以unset
元素输出并将其放在前面:
$input = array(
"one" => "element one",
"two" => "element two",
"three" => "element three",
);
$key = "two";
$element = $input[$key];
unset($input[$key]);
// Complicated associative array unshift:
$input = array_reverse($input);
$input[$key] = $element;
$input = array_reverse($input);
print_r($input);