如何在 PHP 关联数组中存储键和值?
How to store key and value in PHP Associative Array?
我有一个PHP代码
$brandNames = array();
foreach ($maufacturers as $manu) {
array_push($brandNames, array($manu->getTitle() => $manu->getUrl()));
}
print_r($brandNames);
我得到的输出为
Array
(
[0] => Array
(
[key0] => val0
)
[1] => Array
(
[key1] => val1
)
[2] => Array
(
[key2] => val2
)
)
我需要输出为
Array
(
[key0] => val0
[key1] => val1
[key2] => val2
[key3] => val3
)
不是嵌套数组
只是一个包装器数组中的所有键和值。
$brandNames = array();
foreach ($maufacturers as $manu) {
$brandNames[$manu->getTitle()] = $manu->getUrl();
}
print_r($brandNames);
将您的代码更改为:
$brandNames = array();
foreach ($maufacturers as $key => $manu) {
$brandNames[$manu->getTitle()] = $manu->getUrl();
}
print_r($brandNames);
我有一个PHP代码
$brandNames = array();
foreach ($maufacturers as $manu) {
array_push($brandNames, array($manu->getTitle() => $manu->getUrl()));
}
print_r($brandNames);
我得到的输出为
Array
(
[0] => Array
(
[key0] => val0
)
[1] => Array
(
[key1] => val1
)
[2] => Array
(
[key2] => val2
)
)
我需要输出为
Array
(
[key0] => val0
[key1] => val1
[key2] => val2
[key3] => val3
)
不是嵌套数组 只是一个包装器数组中的所有键和值。
$brandNames = array();
foreach ($maufacturers as $manu) {
$brandNames[$manu->getTitle()] = $manu->getUrl();
}
print_r($brandNames);
将您的代码更改为:
$brandNames = array();
foreach ($maufacturers as $key => $manu) {
$brandNames[$manu->getTitle()] = $manu->getUrl();
}
print_r($brandNames);