Jump to content

Change array Values to Keys


SeanHarding

Recommended Posts

I need some help converting my captured array values into keys and later add arrays as the values.

 

This might help explain what I'm looking for:

 

I currently have

Array
(
    [0] => Meat
    [1] => Veg
)

 

But I'm after

Array
(
    Meat => 
    Veg =>
)

 

My end result will be:

[Veg] => Array
                (
                    [Potatoe] => 12
                    [Cabbage] => 24
                    [Cucumber] => 56
                )

[Meat] => Array
                (
                    [Chicken] => 23
                    [beef] => 90
                )

 

I think either array_values() may help but I'm not too sure how to use it.

Link to comment
https://forums.phpfreaks.com/topic/251611-change-array-values-to-keys/
Share on other sites

For the first part of your quetions, you could use a foreach() loop to create the associative array. For example:

 

<?php
//INITIALIZE VARIABLES
$originalArray = array('meat', 'veggies', 'candy');
$newArray      = array();

//CREATE THE ASSOCIATIVE ARRAY
foreach($originalArray as $currItem) {
$newArray[$currItem] = '';
}

//SHOW VARIABLES
var_dump($originalArray) . '<br />';
var_dump($newArray);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.