简体   繁体   English

如何用变量填充多维关联数组项?

[英]How to populate a multi-dimensional associative array item with variables?

I'm trying to populate a multi-dimensional associative array item in PHP with the following variables: 我正在尝试使用以下变量填充PHP中的多维关联数组项:

$number = 1;
$status = 'active';

My array item is currently 'hard-coded' like this: 我的数组项目当前是“硬编码”的,如下所示:

$settings['1']['active'];

How can I replace the '1' and 'active' with $number and $status ? 如何用$number$status替换'1''active'

I've tried the following but am not sure if it is the right way to do it: 我已经尝试了以下方法,但是不确定是否是正确的方法:

$settings['$number']['$status'];

You can't interpolate values in strings defined with single quotes, you should use double " : 您不能在用单引号定义的字符串中插值,应使用double "

$settings["$number"]["$status"];

or 要么

$settings["{$number}"]["{$status}"];

In your case they are not necessary at all : 就您而言,它们根本不是必需的:

 $settings[$number][$status];

Close! 关! Try: 尝试:

$settings[$number][$status];

( Note: When you start indexing arrays with variables, it would be good to first check that the element exists in the array with array_key_exists() http://us3.php.net//manual/en/function.array-key-exists.php ) 注意:当您开始使用变量为数组建立索引时,最好先使用array_key_exists() http://us3.php.net//manual/en/function.array-key-检查数组中的元素是否存在exist.php

PHP doesn't actually have indexes for arrays, so $settings[1] and $settings['1'] will function the same way. PHP实际上没有数组的索引,因此$settings[1]$settings['1']作用相同。 If you'd like to read more about it, check out this PHP.net page on arrays . 如果您想了解更多有关它的信息,请查看arrays上的PHP.net页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM