php 在循环中创建没有键的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5750353/
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 22:22:35  来源:igfitidea点击:

Creating an array without keys in a loop

phparrays

提问by jdp

This might be a brain fart, since it's a late day, but I'm stuck here.

这可能是一个脑放屁,因为现在已经很晚了,但我被困在这里。

I need to take a $_POST value from a select box. (It's an array), and convert it to a simple array that doesn't have any keys.

我需要从选择框中获取 $_POST 值。(它是一个数组),并将其转换为一个没有任何键的简单数组。

Here's the print_r from the item:

这是项目中的 print_r :

Array ( [0] => 19 [1] => 18 [2] => 21 )

Array ( [0] => 19 [1] => 18 [2] => 21 )

Problem is, I need an array that looks like this:

问题是,我需要一个看起来像这样的数组:

Array(19,18,21)

Array(19,18,21)

Whenever I try to foreach() through the form field, I have to do something like this:

每当我尝试通过表单字段 foreach() 时,我必须执行以下操作:

$row[] = $val;

$row[] = $val;

But that leaves me with a numerical index.

但这给我留下了一个数字索引。

What am I missing?

我错过了什么?

Thanks.

谢谢。

采纳答案by Headshota

you can't have an array without keys.

你不能有一个没有键的数组。

Array(19,18,21)

this array has keys 0,1 and 2.

这个数组有键 0,1 和 2。

回答by KingCrunch

Arrays (in PHP) always have (at least) numeric indices. However, you can extract the values via array_values(). This returns only the values of the given array. It of course has indices, but they are continous and they are numeric. Thats the most simple array representation you can have in PHP.

数组(在 PHP 中)总是(至少)有数字索引。但是,您可以通过array_values()提取值。这仅返回给定数组的值。它当然有索引,但它们是连续的并且是数字的。这是您可以在 PHP 中拥有的最简单的数组表示。

Update, just to make that clear: You cannot have an array without indices in PHP (as far as I know in any other language thats quite the same), because internaly arrays are always hashmaps and hashmaps always needs a key. The "most common key" are indices. You cannot omit the "keys". On the other side I dont the any reason why one should want it. If you dont want to use the keys, just dont use the keys and thats really all. PHP is quite gentle in this point.

更新,只是为了说明这一点:在 PHP 中不能有没有索引的数组(据我所知,在任何其他语言中都是相同的),因为内部数组总是哈希图,而哈希图总是需要一个键。“最常用的键”是索引。您不能省略“键”。另一方面,我没有任何理由想要它。如果您不想使用钥匙,就不要使用钥匙,仅此而已。PHP 在这一点上非常温和。

回答by hounded

The closest you are going to get is to combine so your keys are your values

您将获得的最接近的是组合,因此您的键就是您的值

array_combine($array1,$array1)