首页 > 解决方案 > 我如何在 php 中为字符串写这个并且不给我错误

问题描述

$array_names=array("phone","car","house");

我有这个字符串: $phone_[$jr]

但是带有字符串的字符串称为电话它是值的名称,我想使用其他名称来获取值,因此有必要这样写:

${$phone}

它需要在这个字符串中使用其他东西的问题:

${$phone}_[$jr]

这给了我错误

我看到了“_”的问题,但我需要使用,我的问题是关于我如何需要正确的工作

${$电话}_[$jr]

在其他情况下,我需要使用:

${$house}_[$jr]

ETC, .....

谢谢

标签: phparraysstring

解决方案


我假设你有这样的场景:

// this is the array you are trying to access dynamically
$bar_ = [];

// this will hold the first part of the variable name
$phone = 'bar';

// and this is how you would build the string which is the full name of the array
// You can then use it to access one of its elements.
${$phone.'_'}[1] = 'f';

推荐阅读