[英]PHP: Multidimensional array, multidimensional keys?
$products = array(
'paper' => "Paper Section" => array
(
'copier' => "Copier and Multipurpose",
'inkjet' => "Inkjet Printer",
),
'pens' => "Pen Section" => array
(
'ball' => "Ballpoint Pens",
'hilite' => "Highlighters"
),
'misc' => "Miscellaneous Section" => array
(
'tape' => "Sticky Tape",
'glue' => "Adhesive"
)
);
echo "<pre>";
foreach ($products as $section => $items)
foreach ($items as $key => $value)
echo "$section:\t$key\t($value)<br />";
echo "</pre>";
顯然我在這里要做的是為$ section集分配索引,並且我在嘗試這樣做時遇到錯誤。 有沒有其他方法可以做到這一點,還是在PHP中是不可能的?
$products = array(
'paper' => array(
'title' => "Paper Section",
'copier' => "Copier and Multipurpose",
'inkjet' => "Inkjet Printer"
)
);
比如上面的東西。 另一個選擇是添加另一個維度:
$products = array(
'paper' => array(
'meta' => array(
'title' => "Paper Section"
),
'data' => array(
'copier' => "Copier and Multipurpose",
'inkjet' => "Inkjet Printer"
)
)
);
你想要做的是你的數組中的另一個維度。 這就是解決問題的方法。
<?php
$products = array(
'paper' => array(
// --------^^^^^
'Paper Section' => array(
'copier' => 'Copier and Multipurpose',
'inkjet' => 'Inkjet Printer',
),
)
);
var_dump($products);
PS:更好地格式化(和縮進)代碼會更容易。
不是真的了解你想要達到的目標,我還是會試一試。 下面,我重新構建了數據:
$products = array(
'paper' => array(
'Paper Section',
array (
'copier' => "Copier and Multipurpose",
'inkjet' => "Inkjet Printer"
)
),
'pens' => array(
'Pen Section',
array (
'ball' => "Ballpoint Pens",
'hilite' => "Highlighters"
)
),
'misc' => array(
'Miscellaneous Section',
array (
'tape' => "Sticky Tape",
'glue' => "Adhesive"
)
)
);
foreach ($products as $sectionKey => $line) {
foreach ($line[1] as $key => $value) {
echo $sectionKey . ":\t" . $line[0] . ":\t$key\t($value)\n";
}
}
您可以在Ideone上看到演示 。
$products = array(
'paper' => array(
"Paper Section" => array
(
'copier' => "Copier and Multipurpose",
'inkjet' => "Inkjet Printer",
)
),
'pens' => array(
"Pen Section" => array
(
'ball' => "Ballpoint Pens",
'hilite' => "Highlighters"
),
),
'misc' => array(
"Miscellaneous Section" => array
(
'tape' => "Sticky Tape",
'glue' => "Adhesive"
)
)
);
正如其他人提到的那樣,你需要將它包裝在另一個關聯數組中。
但是,我覺得你試圖將最深的關聯數組一次分配給兩個鍵。 如果是這種情況,你不能在PHP的數組聲明中做到這一點,你必須手動做一些事情,比如:
$products = array();
$products['Misc'] = $products['Miscellaneous Section'] = array(
'tape' => "Sticky Tape",
'glue' => "Adhesive"
);
var_dump($products);
好吧,對我來說,你要做的事情遠非顯而易見,但你的語法是錯誤的:數組的構建類似於'key'=>'value'
,因為它是一個鍵/值對你有:
'paper' => "Paper Section" => array()
key->value->value
。 那不行。
也:
echo "
";
可能:
echo "\n";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.