English 中文(简体)
PHP:如何将变量放入数组中?
原标题:PHP: How to put a variable in an array?

只是一个快速的新手PHP语法问题。

我有一个变量,让我们称之为$tabs,它总是包含一个由逗号分隔的数字字符串,如下所示:24,35,43,21

我还有一个变量,它是一个数组:

$args = array( post_type  =>  page ,  post__in  => array(27,19,29),  order  =>  ASC );

那当然是WordPress。我需要做的是将$tabs变量(数字)的内容放在数组中数字所在的位置。我对PHP相当陌生,只知道如何修改一些东西,但这一点我搞不清楚,不知道它的语法应该如何。

有人能帮忙吗?谢谢

最佳回答
$args[ post__in ] = array_merge($args[ post__in ], explode( , , $tabs));

让我们来解释一下我做了什么,这样你就可以了解一两件事:

  1. explode( , , $tabs) splits a string into pieces at a separator and puts that pieces in an array.
  2. array_merge($arr1, $arr2) will merge the two arrays.
  3. $args[ post__in ] will access an array element specified by a key.

请注意,在这种情况下,array_merge只会附加值,结果可能会出现重复的数字。要消除重复项,只需将合并封装在<code>array_unique

$args[ post__in ] = array_unique(array_merge($args[ post__in ], explode( , , $tabs)));

当然,当你只想用全新的数字替换这些数字时,最琐碎的情况是

$args[ post__in ] = explode(`,`, $tabs);
问题回答

$args[post__in]=爆炸(“,”,$tab)





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...