PHP:: 无法检索数组内的所有值

PHP:: cannot retrieve all values inside array

这是我的简单代码:

<?php

$components=array(
1 => 'Carrot', 'Apple', 'Orange',
2 => 'Boiled Egg', 'Omelet',
3 => 'Ice Cream', 'Pancake', 'Watermelon'
);

echo'<pre>';
var_dump($components);
echo'</pre>';

输出:

array(6) {
  [1]=>
  string(6) "Carrot"
  [2]=>
  string(10) "Boiled Egg"
  [3]=>
  string(9) "Ice Cream"
  [4]=>
  string(6) "Omelet"
  [5]=>
  string(7) "Pancake"
  [6]=>
  string(10) "Watermelon"
}
  1. 'Apple' & 'Orange' 在哪里?
  2. 为什么我无法从中检索特定值(例如:$components[1][2] = 'r'):/ 为什么?!

像这样创建一个数组,

$components=array(
  1 => ['Carrot', 'Apple', 'Orange'],
  2 => ['Boiled Egg', 'Omelet'],
  3 => ['Ice Cream', 'Pancake', 'Watermelon']
);

现在检查你的数组。

根据您给定的语法,它形成的是一维数组,而不是多维数组。

试试这个:

$components=array(
    1 => array('Carrot', 'Apple', 'Orange'),
    2 => array('Boiled Egg', 'Omelet'),
    3 => array('Ice Cream', 'Pancake', 'Watermelon')
 );

您需要像这样组织数组:

$components = array(
   1 => array(
         1 => 'Carrot',
         2 => 'Apple',
         3 => 'Orange'
   ),
   2 => array(
         1 => 'Boiled Egg',
         2 => 'Omelet'
   ),
   3 => array(
         1 => 'Ice Cream',
         2 => 'Pancake',
         3 => 'Watermelon'
   ),
);

那么您将可以获得:$components[1][2] = 'Apple'

你可以像这样使用字符串到数组索引中

 <?php
$components=array(
1 => ['Carrot', 'Apple', 'Orange'],
2 => ['Boiled Egg', 'Omelet'],
3 => ['Ice Cream', 'Pancake', 'Watermelon']
);

echo "<pre>";
print_R($components);

?>