如何在PHP中使用数组内的字符串中的变量

时间:2015-04-15 03:56:02

标签: php arrays variables

我有以下功能,我将重复多次,但更改数组值。

register_field_group(array (
    'id' => 'acf_page-options-cat-work',
    'title' => 'Featured Posts',
    'fields' => array (
        array (
            'key' => 'field_5262q874nq12',
            'label' => 'Featured Posts',
            'name' => 'featured_posts',
            'type' => 'repeater',
            'sub_fields' => array (
                array (
                    'key' => 'field_5262q874nq13',
                    'label' => 'Post',
                    'name' => 'featured_post',
                    'type' => 'post_object',
                    'post_type' => array (
                        0 => 'post',
                    ),
                    'allow_null' => 0,
                    'multiple' => 0
                )
            ),
            'row_min' => 0,
            'row_limit' => '',
            'layout' => 'row',
            'button_label' => 'Add a post',
        )
    )
));

我希望'key'元素是动态的。我尝试使用花括号来插入变量,如下所示:

array(
     'key' => 'string{$variable}'
)

但它不起作用......

$rand_string = 'asdasdasda';

register_field_group(array (
    'id' => 'acf_page-options-cat-work',
    'title' => 'Featured Posts',
    'fields' => array (
        array (
            'key' => 'field_526{$rand_string}12',
            'label' => 'Featured Posts',
            'name' => 'featured_posts',
            'type' => 'repeater',
            'sub_fields' => array (
                array (
                    'key' => 'field_526{$rand_string}13',
                    'label' => 'Post',
                    'name' => 'featured_post',
                    'type' => 'post_object',
                    'post_type' => array (
                        0 => 'post',
                    ),
                    'allow_null' => 0,
                    'multiple' => 0
                )
            ),
            'row_min' => 0,
            'row_limit' => '',
            'layout' => 'row',
            'button_label' => 'Add a post',
        )
    )
));

如何在数组内的字符串中使用变量?

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试使用双引号

$cat = "meow";
$test = array(
     'key' => "string {$cat}"
);

echo "<pre>";
print_r($test);
echo "</pre>";

希望它对你有用。