PlayHardGoPro
PlayHardGoPro

Reputation: 2933

Insert a new array inside an Associative Array

I tried to insert a new array inside my multidimensional/Associative array. BUt it does not work, neither array_push() does. My current code is as follow:

$myJson = array(
  array (
    'id' => 1,
    'name' => 'Jane Doe', 
    'age' => 26
  ),
  array (
    'id' => 2,
    'name' => 'Josélito',
    'age' => 35
  )
);


$myAr = array(
  'id' => 5,
  'channel' => 'pimbaTv',
  'followers' => 15014
);

foreach($myJson AS $js) {
  $js['event'][] = $myAr;
  //$js['event'] = $myAr;
}

So I would have something like this:

  array (
    'id' => 1,
    'name' => 'Jane Doe', 
    'age' => 26,
    'event' => array(
       'id' => 5,
       'channel' => 'pimbaTv',
       'followers' => 15014
     );
  ),
  array (
    'id' => 2,
    'name' => 'Josélito',
    'age' => 35,
    'event' => array(
       'id' => 5,
       'channel' => 'pimbaTv',
       'followers' => 15014
     );
  )

I'm trying everything I can find but still no solution.

Upvotes: 0

Views: 90

Answers (4)

Sigma
Sigma

Reputation: 407

The array_push() function is normally used to push new data in the array but must have a sequential index: $arr[0] , $ar[1].. etc.

You cannot use it in associative array directly. But looking to your array structure, since your sub array have this kind of index you can still use array push but you must specify the index. This is an example:

array_push($myJson["event"], $myAr);

Hope it is more clear for you.

Upvotes: 1

Madhur Bhaiya
Madhur Bhaiya

Reputation: 28834

You need to access your original array $myJson using $key from the loop, for assigning new values. By default, $value inside a foreach loop, are not passed by reference.

Do the following:

foreach($myJson AS $key => $value) {
  $myJson[$key]['event'] = $myAr;
}

You can see other answers as well, utilizing passing by reference.

Upvotes: 1

Philoupe
Philoupe

Reputation: 101

In new php versions, you should use references to edit its content.

Instead of doing :

foreach($myJson AS $js) {
    $js['event'][] = $myAr;
}

You shoud do :

foreach($myJson AS &$js) {
    $js['event'][] = $myAr;
}

http://php.net/manual/en/control-structures.foreach.php

"In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference."

Upvotes: 1

Divyesh Prajapati
Divyesh Prajapati

Reputation: 985

You can use pass by reference to array in for loop like this. For reference PHP Pass by reference in foreach

foreach($myJson AS &$js) {
    $js['event'] = $myAr;
}

Upvotes: 2

Related Questions