PHP:如何把一个变量数组? [英] PHP: How to put a variable in an array?
问题描述
只是一个快速的新手PHP语法问题。
我有一个变量,我们称之为 $标签页
总是包含用逗号分隔的一串数字,像这样: 24,35, 43,21
我也有一个变量,它是一个数组:
的$ args =阵列('post_type'=>'页面','post__in'=>阵列(27,19,29),秩序= GT;'ASC ');
这是当然的Word preSS的。我需要做的,是放在 $标签页
变量(数字)其中数组里面的数字内容。我是相当新的PHP,只知道如何修改一些东西,但是这个我想不通,不知道它的语法怎样走。
任何人能帮助吗?谢谢你。
的$ args ['post__in'] = array_merge(的$ args ['post__in'],爆炸('', $标签));
让我们来解释一下我这样做了,你可以拿起一两件事:
-
爆炸('',$标签)
将一个字符串插入到分隔件,并把那件在数组中。 -
array_merge($ ARR1,$ ARR2)
将合并两个数组。 -
的$ args ['post__in']
将访问一个键指定的数组元素。
注意array_merge,在这种情况下,只是附加价值,你可能出现重复的数字。为了摆脱重复的只是包装在 array_unique
合并。像这样:
的$ args ['post__in'] = array_unique(array_merge(的$ args ['post__in'],爆炸('',$标签)));
当然,如果你只是想用新的品牌来代替这些数字琐碎的情况下
的$ args ['post__in'] =爆炸(`,`,$标签);
Just a quick newbie PHP syntax question.
I have a variable, let's call it $tabs
which always contains a string of numbers separated by commas, like so: 24,35,43,21
I also have a variable that's an array:
$args = array('post_type' => 'page', 'post__in' => array(27,19,29), 'order' => 'ASC');
That's of course WordPress. What I need to do, is place the content of the $tabs
variable (numbers) where the numbers inside the array are. I'm rather new to PHP, only understand how to modify some things, but this I can't figure out, no idea how the syntax for it should go.
Anyone able to help? Thanks.
$args['post__in'] = array_merge($args['post__in'], explode(',', $tabs));
Let's explain what I did so you may pick up a thing or two:
explode(',', $tabs)
splits a string into pieces at a separator and puts that pieces in an array.array_merge($arr1, $arr2)
will merge the two arrays.$args['post__in']
will access an array element specified by a key.
Note that array_merge, in this case, will just append the values and you may end up with duplicate numbers. To get rid of duplicates just wrap the merge in array_unique
. Like so:
$args['post__in'] = array_unique(array_merge($args['post__in'], explode(',', $tabs)));
And of course, the trivial case when you just want to replace those numbers with brand new ones is
$args['post__in'] = explode(`,`, $tabs);
这篇关于PHP:如何把一个变量数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!