[英]How to remove keys from array to create list of values only in PHP?
I have a method that passes in an array, and requires a list of int
numbers separated by commas to be taken from the passed in array.我有一个传入数组的方法,并且需要从传入的数组中获取由逗号分隔的
int
列表。 When I pass in the array, I obviously see the key=>value
relationship like:当我传入数组时,我显然看到了
key=>value
关系,如:
0 => 38
1 => 39
2 => 40
3 => 41
But in my method, I need to remove the key for each item in the array, and build a literal list of int numbers - not a string - to be used in my method like the following:但是在我的方法中,我需要删除数组中每个项目的键,并构建一个 int 数字的文字列表 - 而不是字符串 - 在我的方法中使用,如下所示:
[38, 39, 40, 41]
I can't do a foreach
and simply echo each value, as my method only runs once and requires a literal list of int
s followed by commas to be used further down deep in my method.我不能执行
foreach
并简单地回显每个值,因为我的方法只运行一次并且需要一个int
的文字列表,后跟逗号,以便在我的方法中进一步使用。 When I iterate through the array to build a new array, keys are created there too.当我遍历数组以构建新数组时,也会在那里创建键。 I can't simply pass in a string, as that would have quotes at the beginning and end of the string.
我不能简单地传入一个字符串,因为它会在字符串的开头和结尾处有引号。 I'm a bit confused how to approach this.
我有点困惑如何解决这个问题。 Any help would be greatly appreciated.
任何帮助将不胜感激。
$array = [1,2,3,4];
$new_value = implode(',',$array);
Both your arrays are same, [38, 39, 40, 41]
.您的两个数组都相同,
[38, 39, 40, 41]
。 Here 38
is at index 0
, 39
at 1
.这里
38
在index 0
, 39
在1
。 you can use array_values
if you want to pick only array values or reset your index values if they are not aligned ie 0,1,2.如果您只想选择数组值或重置索引值(如果它们未对齐,即 0,1,2),您可以使用
array_values
。 With implode
, you will be converting your array to string which will not include [ ]
.使用
implode
,您将把数组转换为不包含[ ]
字符串。 So you can pass your complete array as it is in your further methods.因此,您可以在进一步的方法中传递完整的数组。 If you want to output it is a string
[38, 39, 40, 41]
then this can be achieved like this.如果你想输出它是一个字符串
[38, 39, 40, 41]
那么这可以像这样实现。
echo '['.implode(", ",$arr).']';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.