Mauzer
Mauzer

Reputation: 35

Insert key value - array in array

I am getting some values (domain names) from a _POST which I have to insert into an "Array in an Array". The array is called $postValues["domainrenewals"] and the I need to create another array inside this one in the format:

domainname => 1 (where 1 is the number of years).n

My code:

foreach ($_POST['renewthesedomains'] as $key => $value) {

   $postValues["domainrenewals"] = array($value => "1");
}

var_dump ($postData);

The var_dump shows that only the last $key -> $value pair is being inserted into $postValues["domainrenewals"]

Any help, much appreciated.

Upvotes: 1

Views: 88

Answers (2)

jake2389
jake2389

Reputation: 1174

In each pass of the foreach loop you're redefining $postValues["domainrenewals"] so of course only the last one is saved... Try doing this:

$postValues["domainrenewals"] = array();

foreach ($_POST['renewthesedomains'] as $key => $value) {
    $postValues["domainrenewals"][$value]  = "1";
}

If you need to add another value to the array I'm assuming it's information of the domain, so you would do something like:

$postValues["domainrenewals"][$value]['your_first_value'] = "1";

// Then for your other value
$postValues["domainrenewals"][$value]['renewalpriceoverride'] = 285.00;

Upvotes: 5

mahethekiller
mahethekiller

Reputation: 514

Try This:

$postValues = array();
$arr=array();

foreach ($_POST['renewthesedomains'] as $value) {
    $arr["domainrenewals"]=$value;
    $arr["no_of_years"]=1;
    $postValues[]  = $arr;
    $arr=array();
}

Upvotes: 0

Related Questions