在PHP中创建唯一的变量名称

时间:2014-12-19 13:58:51

标签: php variables

我有一个可以在每个脚本中多次使用的脚本,脚本的每个实例都需要完成一些php工作,我需要为每个实例变量创建一个唯一的名称,例如。

我需要:

$typedbefore1 = get_post_meta( $text, '_cmb2_typed_text', true );
$typed1 = '"' . implode('","', $typedbefore1) . '"';

$typedbefore2 = get_post_meta( $text, '_cmb2_typed_text', true );
$typed2 = '"' . implode('","', $typedbefore2) . '"';

$typedbefore3 = get_post_meta( $text, '_cmb2_typed_text', true );
$typed3 = '"' . implode('","', $typedbefore3) . '"';

变量$ text是用户生成的数字,因此我可以使用它。例如。

$typedbefore.$text = get_post_meta( $text, '_cmb2_typed_text', true );
$typed.$text = '"' . implode('","', $typedbefore.$text) . '"';

那不行(显然),有办法做我需要的吗?

转换为数组,但我的内爆不起作用:

$typedbefore = array();
$typedbefore[$text] = get_post_meta( $text, '_cmb2_typed_text', true );
$typed = array();
$typed[$text] = '"' . implode('","', $typedbefore[$text]) . '"';

它仍然将$ typed存储为数组,我该如何处理第二部分,以便从$ typedbefore中删除数据?

2 个答案:

答案 0 :(得分:2)

你真的应该使用数组,因为 MightyPork 建议......:

$typedbefore = array();
$typedbefore[$text] = "value";

更新:要回答OP上一个问题:来自here我看到wordpress finction get_post_meta()只有在array的最后一个参数为{{}}时才会返回false {1}}。但是我看到你使用true,所以它应该返回一个值。因此,您不应该使用单个值来使用implode(期望数组作为第二个参数)。 我真的不明白你的最终目标是什么,所以我无法给出更具体的评论,对不起......

答案 1 :(得分:1)

您可以使用变量变量,例如:

$varname = "typedbefore".$text;
echo $$varname;

如果你说:

,这是一样的
echo $typedbefore1 //If $text == 1

请参阅here

但更好的是,如果您正在将数据收集到数组中,并使用它。