简体   繁体   中英

How to store key and value in PHP Associative Array?

I have a PHP Code

$brandNames = array();
foreach ($maufacturers as $manu) {
    array_push($brandNames, array($manu->getTitle() => $manu->getUrl()));
}
print_r($brandNames);

I am getting output as

Array
(
    [0] => Array
        (
            [key0] => val0
        )

    [1] => Array
        (
            [key1] => val1
        )

    [2] => Array
        (
            [key2] => val2
        )
)

I need output as

Array
(
     [key0] => val0
     [key1] => val1
     [key2] => val2
     [key3] => val3
)

Not the nested array Just all keys and values inside one wrapper array.

$brandNames = array();
foreach ($maufacturers as $manu) {
    $brandNames[$manu->getTitle()] = $manu->getUrl();
}
print_r($brandNames);

Change your code to:

$brandNames = array();
foreach ($maufacturers as $key => $manu) {
    $brandNames[$manu->getTitle()] = $manu->getUrl();
}
print_r($brandNames);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM