问题
I have:
$request = Array
(
[ID] => 2264
[SUCCESS] => Array
(
[0] => Array
(
[MESSAGE] => Service Details
[LIST] => Array
(
[retail_name] =>
[credit_admin] => FREE
[credit] => 0
[discount_admin] => 0
[discount] => 0
[cartdiscount] => 0
If I do:
echo $request[ID]; // it says: 2264
echo $request[SUCCESS]; // it says: Array
echo $request[SUCCESS][0][MESSAGE]; // it says: Service Details
But I need to echo "credit" and if I do:
echo $request[SUCCESS][0][LIST]; // I get ERROR
echo $request[SUCCESS][0][LIST][credit]; // I get ERROR
I dont understand why? How can I do it? Thank you
回答1:
Previously every string without quotes was treated like string if there was no Constant defined under this name, but from PHP 7.2 now issues error of level E_WARNING. Why is $foo[bar] wrong?
PHP Warning: Use of undefined constant test - assumed 'test' (this will throw an Error in a future version of PHP)
In this example list is treated as construct list(). Using bare strings in associative arrays as keys is deprecated and should be avoided.
Correct way is to call it with quotes (single or double):
echo $request['SUCCESS'][0]['LIST'];
echo $request['SUCCESS'][0]['LIST']['credit'];
回答2:
You aren't using quotes to specify the array keys. you should use ['ID'] instead of [ID]
PHP fixes this for you and presumes you meant ['ID'] instead of [ID] and trows a notice in the logs
This doen't work for [LIST] however because LIST is a reserved keyword. That means that list has a function in PHP. PHP doesn't know which one you need and doesn't return result.
Change [LIST] to ['LIST'] and you should recieve your values.
Please learn to use arrays with quotes, to prevent errors like this in the future
回答3:
Depends on Your Key and Value
If your array key has a value it will directly output that
for ex
echo $request[ID];
b'coz id directly holds a value;
But
$request[SUCCESS];
// holds an array. you cannot echo a array directly
// to do something like this you will need the key of your inner
// array with outer array in combinations to echo the values
for ex
echo $request[SUCCESS][0]['MESSAGE'];
// Key "O" holds an array also. so you need to use its inner array keys
same needs to be done for
echo $request[SUCCESS][0]['MESSAGE']['LIST']['credit_admin'];
// where again list is a array
来源:https://stackoverflow.com/questions/31333393/php-how-to-echo-value-from-multidimensional-array