在 PHP 中通过整数索引访问关联数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4769148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:18:33  来源:igfitidea点击:

Accessing an associative array by integer index in PHP

php

提问by Marty

I want to set the value of an associative array using the array index of the key/value pair. For example:

我想使用键/值对的数组索引设置关联数组的值。例如:

$my_arr = array( "bling" => "some bling", "bling2" => "lots O bling" );
$my_arr[1] = "not so much bling";  // Would change the value with key bling2.

How can this be accomplish this without using the key string?

如何在不使用密钥字符串的情况下完成此操作?

回答by Donovan

Use array_keys.

使用array_keys

$keys = array_keys($my_arr);
$my_arr[$keys[1]] = "not so much bling";

Hope this helps.

希望这可以帮助。

回答by Gordon

There is no correlation between numeric and associative index keys.

数字索引键和关联索引键之间没有相关性。

When you say you want to set the value of an associative array using the array index of the key/value, then you have to use the given key, setting $array[1]is not the same as setting $array['foo'].

当您说要使用键/值的数组索引设置关联数组的值时,您必须使用给定的键,设置$array[1]与设置不同$array['foo']

Consider this array

考虑这个数组

print_r( array('foo', 'foo' => 'bar', 'baz', 'some' => 'value') );

This will give

这会给

Array
(
    [0] => foo
    [foo] => bar
    [1] => baz
    [some] => value
)

The foo is the second element in the array. That's the offset, but it has nothing to do with the index 1. As you can see, in that array above, index 1 is associated with baz. It is wrong to assume that just because foois the first associative key it has anything to do with the actual numeric key 1. Just like somedoes not correlate to 2.

foo 是数组中的第二个元素。那是偏移量,但它与索引 1 无关。正如您所看到的,在上面的数组中,索引 1 与 相关联baz。假设仅仅因为foo是第一个关联键,它与实际的数字键 1 有任何关系是错误的。就像与some2 不相关。

Likewise, for a mixed array like shown above, the solution with array_keyssuggested elsewhere on this site will not work, because

同样,对于如上所示的混合数组,array_keys本网站其他地方建议的解决方案将不起作用,因为

print_r( array_keys(array('foo', 'foo' => 'bar', 'baz', 'some' => 'value')) );

will give

会给

Array
(
    [0] => 0
    [1] => foo
    [2] => 1
    [3] => some
)

So when you do $array[$keys[1]]you are really doing $array['foo']. But if you wanted to access the second associative value in that array ('some'), you cannot do $array[$keys[2]]because that would evaluate to $array[1]and that's baz.

所以当你这样做时,$array[$keys[1]]你真的在做$array['foo']。但是,如果你想要一个阵列(在访问第二个关联值'some'),你不能这样做$array[$keys[2]],因为这将评估为$array[1]和的baz

The Offset of an element is completely unrelated to it's key or value

元素的偏移量与它的键或值完全无关

print_r(
    array(
        100    => 'foo',
        'foo'  => 'bar',
        50     => 'baz',
        'some' => 'value'
    )
);

really means

真正意思

Array
( //key       value     offset/position
    [100]  => foo       // 0
    [foo]  => bar       // 1
    [50]   => baz       // 2
    [some] => value     // 3
)

which means the element at offset 0 is foo although it's key is 100. If you want to extract elements from an array by offset, you have to use

这意味着偏移量 0 处的元素是 foo 虽然它的键是 100。如果你想通过偏移量从数组中提取元素,你必须使用

$third = array_splice($array, 2, 1);
echo $third[0]; // baz

This would create an array holding only the element at the third position.

这将创建一个仅包含第三个位置的元素的数组。

Or you could use an ArrayIterator. The ArrayIteratorimplements a Seekableinterface that lets you seek to a specific position/offset in the array and then fetch that:

或者你可以使用一个ArrayIterator. 在ArrayIterator实现了一个Seekable阵列中的界面,可以让你寻找到特定位置/偏移量,然后获取该:

$iterator = new ArrayIterator($array);
$iterator->seek(3);
echo $iterator->current(); // value

回答by Richard A Quadling

Whilst array_keys()allows access to the nth key, array_valueswill give you the nth value.

虽然array_keys()允许访问第 n 个键,但array_values会给你第 n 个值。

<?php
$array = [
   0     => 'Zero',
   '1'   => 'One',
   'Two' => 'Two',
];
echo array_values($array)[2];
?>

will output 'Two'.

将输出“两个”。

Is there an advantage of one over the other? Well, the only minor one I can see is the number of array accesses.

一个比另一个有优势吗?好吧,我能看到的唯一次要的是数组访问的次数。

With array_keys()you need to 3.

随着array_keys()你需要 3。

  1. Get the keys from the data array.
  2. Get the nth key from the list of keys.
  3. Get the value using the nth key from the data array.
  1. 从数据数组中获取键。
  2. 从键列表中获取第 n 个键。
  3. 使用数据数组中的第 n 个键获取值。

With array_values(), you only need 2.

使用array_values(),您只需要 2 个。

  1. Get the values from the data array.
  2. Get the nth value from the list of values.
  1. 从数据数组中获取值。
  2. 从值列表中获取第 n 个值。

But, on the other hand, keys are normally smaller and the data could be hugely nested, so, on balance, using the array_keys()is probably safer.

但是,另一方面,键通常较小,并且数据可以大量嵌套,因此,总的来说,使用array_keys()可能更安全。

回答by Jesse

If the array is large, both array_keysand array_valueswill be wasteful since they will allocate a new array the same size as the original, just to get the nthkey (or value).

如果数组很大,既有array_keysarray_values将是浪费的,因为他们将分配一个新的数组大小相同,原来,只是为了让第n个键(或价值)。

array_sliceaccepts an integer offset and works on associative arrays. You can use it to get (and set) the nthkey in constant time.

array_slice接受整数偏移量并处理关联数组。您可以使用它在恒定时间内获取(和设置)第n 个键。

// This will at most allocate 2 temporary arrays of 1 element each
$key = array_keys(array_slice($array, $n, 1, true))[0];

$array[$key] = $value;

回答by Murali krishna

Try this. It works for you.

尝试这个。它对你有用。

$result= array_values($my_arr); // Array with indexes you need

回答by phreditor

Another possibility is to convert it to a normal array:

另一种可能性是将其转换为普通数组:

$arraybuff = implode("~~~",$my_arr);
$my_arr = explode("~~~",$arraybuff);

$arraybuff = implode("~~~",$my_arr);
$my_arr =explode("~~~",$arraybuff);

Where "~~~" is a delimiter that wont occur in your data.

其中“~~~”是数据中不会出现的分隔符。

Now you can access the array using numerical indexes equal to the offsets.

现在您可以使用等于偏移量的数字索引访问数组。

If you still need to retain your associative array, just assign it to a different variable.

如果您仍然需要保留关联数组,只需将其分配给不同的变量即可。