Place one array inside another

Asked

Viewed 85 times

-1

How do I add the "favorite" array to the "colors" array"?

$a1['cores']=array("vermelho","amerelo","preto");
$a2['favoritas']=array("amerelo","preto");

I’ve tried with array_merge

array_merge($a1,$a2);
print_r($a1);

with array_push

array_push($a1,$a2);
print_r($a1);

but it won’t.

The result I want.

  Array ( [cores] => Array ( [0] => vermelho [1] => amerelo [2] => preto [favoritas] => Array ( [0] => amerelo [1] => preto ) ) ) 
  • Do you need to declare 2 Arrays? If you do $a['cores']=array("vermelho","amerelo","preto"); $a['favoritas']=array("amerelo","preto"); You will get the result unless you need the same two lists.

  • Unfortunately it needs. :(

  • Creates a third, a3['cores'] = a1; a3['favoritas'] = a2;

  • Roger, there’s something wrong there. The result was Array ( [colors] => Array ( [colors] => Array ( [0] => red [1] => amerelo [2] => black ) [favorites] => Array ( [favorites] => Array ( [0] => amerelo [1] => black ) ) )

  • Because you declare a1 and a2 with these indexes.. Now it’s easy.. hehe

  • I’m sorry, I don’t understand. but your answer doesn’t fit my question. I put your answer to run and it’s not equal(or similar) to what I want.

Show 1 more comment

3 answers

0

good morning a very simple way of doing this and

$a1['cores']=["vermelho","amerelo","preto"];
$a2['favoritas']=["amerelo","preto"];
$a2['favoritas']['cores']=$a1['cores'];
  • clone, I will mark as solved but you changed the structure of the code I put and this is not very nice for people who can not change, in my case I can change and so I managed to solve the problem. only changes the code to: $a1['colors']['favourites']=$a2['favourites']; print_r($a1);

0

Create one with both arrays see in ideone

$a1['cores']=array("vermelho","amerelo","preto");
 
$a2['favoritas']=array("amerelo","preto");
 
$resultQueEuQuero = array($a1, $a2);
print_r($resultQueEuQuero);
die;
  • Good afternoon, leo." Favorites" has to stay inside colors. but I’ve solved the problem. thanks for the contribution.

0

I think what you’re looking for is this. Remember that the array_merge has no reference to the array passed, this method has the return with the merged array.

$a1['cores']=array("vermelho","amerelo","preto");
$a2['favoritas']=array("amerelo","preto");
$a1 = array_merge($a1['cores'], $a2);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.