PHP数组,如何访问键和值

时间:2014-07-14 13:48:03

标签: php arrays multidimensional-array

尝试学习多维数组,但似乎一直在努力去访问它们。我仍然没有掌握如何使用索引,键,值访问它们。

我如何找到实际的单词" 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"而不是索引号?

3 个答案:

答案 0 :(得分:1)

你有一个数组数组,因此你需要两个循环。

foreach ($shop as $item) {
    foreach ($item as $key => $value) {
        echo $key;
        echo $value;
    }
}

答案 1 :(得分:0)

您可以通过$ 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'];
}

希望这有用。

答案 2 :(得分:0)

试试这个 -

$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
        )

)