简体   繁体   中英

Insert multidimensional associative array into multidimensional associative PHP

Hi all I have the following (this is an example of what I am attempting what I actually have is allot larger):

$array= array();
array_push($array,$var['bookshopname']);
$array[$var['bookshopname']]=array('opentime'=>$var1,'closetime'=>$var2);

foreach($array as $var)
{
print_r($var);
}

I get:

Storename1
Array ( [opentime] => 12 [closetime] => 17 ) 
Storename2
Array ( [opentime] => 13 [closetime] => 19 ) 

So if I count the array there are 4 elements If I attempted the following

foreach($array as $var)
{
print_r($var['opentime']);
}

It breaks on the first result (Storename1).

I want the following

 array(
       Storename1 => array(opentime => ...)
       Storename2 => array(opentime => ...)
      )

and I am getting this:

 array(
       [0] => Storename1[Storename1] => Array ( [opentime ] =>....
       [1] => Storename2[Storename2] => Array ( [opentime ] =>....
      )

I cant quite figure out why it creates these two extra results with the names

In response to Oriol

When I try to update it further down the line

for example:

$array[$var['bookshopname']] = 
      array('opentime'=>$array[$var['bookshopname']]['opentime']+1,
            'closetime'=>$array[$var['bookshopname']]['closetime']-2);

Then it does not update the values but rather just replaces with the values I am trying to add or subtract

Just use

$array= array();
$array[$var['bookshopname']]=array('opentime'=>$var1,'closetime'=>$var2);

Your code creates extra entries because of

array_push($array,$var['bookshopname']);

Maybe you should read http://php.net/manual/en/function.array-push.php to understand better what array_push does

Edit :

If you just want to modify the values, try this

$array[$var['bookshopname']]['opentime'] += 1;
$array[$var['bookshopname']]['closetime'] -= 2;

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