尝试学习多维数组,但似乎总是难以访问它们。我还没有掌握如何使用索引,键,值来访问它们。
我如何得到实际的单词"Title"和它的值?
这里有一个我正在玩的。
$shop = array( array( "Title" => "rose",
"Price" => 1.25,
"Number" => 15
),
array( "Title" => "daisy",
"Price" => 0.75,
"Number" => 25,
),
array( "Title" => "orchid",
"Price" => 1.15,
"Number" => 7
)
);
Which prints a structure such as this:
Array
(
[0] => Array
(
[Title] => rose
[Price] => 1.25
[Number] => 15
)
[1] => Array
(
[Title] => daisy
[Price] => 0.75
[Number] => 25
)
[2] => Array
(
[Title] => orchid
[Price] => 1.15
[Number] => 7
)
)
echo $shop[0][0][0]; //I Expect "rose" but I get "Undefined offset: 0"
echo $shop['Price']; //I expect 1.25 but I get "Undefined index: Price"
foreach($shop as $key=>$value)
{
echo $key; //I expect the key values "Title/Price/Number" instead I get Index numbers 0 1 2
echo $value; //I expect all values of keys e.g. "rose",1.25,15/"daisy",0.75,25/"orchid",1.15,7 Instead I get Array to string conversion error
}
我要做的是,从商店数组中获取所有的标题和值,并将其放入一个名为$x = array()的新数组中;然后从不同的数组中获取一个汽车键/值,并将它们组合在一起。
所以新的数组最终看起来像这样:
Array
(
[0] => Array
(
[Title] => rose //from $shop array
[Car] => Mercedez //from $car array
)
[1] => Array
(
[Title] => daisy //from $shop array
[Car] => Ford //from $car array
)
[2] => Array
(
[Title] => orchid //from $shop array
[Car] => Bentley //from $car array
)
)
还有一种方法可以访问键"title"的实际名称,而不是索引号?
你有一个数组的数组,因此你需要两个循环。
foreach ($shop as $item) {
foreach ($item as $key => $value) {
echo $key;
echo $value;
}
}
试试这个-
$newarray = array();
foreach($shop as $key=>$value) {
$newarray[$key]['Title'] = $value['Title'];
$newarray[$key]['Number'] = $value['Number'];
}
echo "<pre>";print_r($newarray);
这里,$newarray
将给出如下输出:
Array
(
[0] => Array
(
[Title] => rose
[Number] => 15
)
[1] => Array
(
[Title] => daisy
[Number] => 25
)
[2] => Array
(
[Title] => orchid
[Number] => 7
)
)
可以通过$shop[0]['Title']访问0表示数组中的第一项,该项也是一个数组,其中包含字符串键,因此'title'作为第二级。
使用:
//Syntax array as key => value (value is in this case also an array)
foreach($shop as $iterator_level1 => $shop_set){
//so you can access the 2. level by string key.
echo $shop_set['title'];
}
希望对大家有帮助