PHP数组,如何访问键和值 [英] PHP array's, how to access keys and values
问题描述
尝试学习多维数组,但似乎在访问它们时经常遇到困难。我仍然不了解如何使用索引,键,值访问它们。
Trying to learn multidimensional arrays but seem to constantly struggle with accessing them. I still have not got grasps of how you access them using index, keys, values.
我如何获得实际的标题一词及其价值?
How do I get to the actual word "Title" and it's value?
这里我有一个
$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
}
我想做的是从shop数组中获取所有标题和值,并将其放入一个新的$ x = array();数组中。然后从其他数组中获取汽车钥匙/值,并将其组合在一起。
What I am trying to do, is take all the title and value from the shop array, and put it into a new array called $x = array(); and then take a car key/value from a different array and combine them together.
所以新数组最终看起来像这样:
so the new array ends up looking like this:
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的实际名称而不是索引号吗?
Also is there a way to access the actual name of the key "title" and not a index number?
推荐答案
尝试一下-
$newarray = array();
foreach($shop as $key=>$value) {
$newarray[$key]['Title'] = $value['Title'];
$newarray[$key]['Number'] = $value['Number'];
}
echo "<pre>";print_r($newarray);
在这里, $ newarray
将为您提供输出
Here, $newarray
will give you output like this.
Array
(
[0] => Array
(
[Title] => rose
[Number] => 15
)
[1] => Array
(
[Title] => daisy
[Number] => 25
)
[2] => Array
(
[Title] => orchid
[Number] => 7
)
)
这篇关于PHP数组,如何访问键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!