Php add to multidimensional array

I have a multidimensional array $md_array and I want to add more elements to the sub-arrays recipe_type and cuisine coming from a loop that reads data from a table.

In the loop, I create a new table $newdata for each row:

$newdata =  array (
          'wpseo_title' => 'test',
          'wpseo_desc' => 'test',
          'wpseo_metakey' => 'test'
        );

and then, using array_push() I need to append the $newdata arrays to the following multidimensional array:

$md_array= array (
     'recipe_type' => 
      array (
        18 => 
        array (
          'wpseo_title' => 'Salads',
          'wpseo_desc' => 'Hundreads of recipes for Salads',
          'wpseo_metakey' => ''
        ),
        19 => 
        array (
          'wpseo_title' => 'Main dishes',
          'wpseo_desc' => 'Hundreads of recipes for Main dishes',
          'wpseo_metakey' => ''
        )
      ),
     'cuisine' => 
      array (
        22 => 
        array (
          'wpseo_title' => 'Italian',
          'wpseo_desc' => 'Secrets from Sicily in a click',
          'wpseo_metakey' => ''
        ),
        23 => 
        array (
          'wpseo_title' => 'Chinese',
          'wpseo_desc' => 'Oriental dishes were never this easy to make',
          'wpseo_metakey' => ''
        ),
        24 => 
        array (
          'wpseo_title' => 'Greek',
          'wpseo_desc' => 'Traditional Greek flavors in easy to make recipies',
          'wpseo_metakey' => ''
        )
      ) 
    );

Whats the syntax for adding a new element (array) to the recipe_type array with array_push? I could never get my head around multidimensional arrays and I'm a bit confused.


In the previous pages, we have described arrays that are a single list of key/value pairs.

However, sometimes you want to store values with more than one key. For this, we have multidimensional arrays.


PHP - Multidimensional Arrays

A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

The dimension of an array indicates the number of indices you need to select an element.

  • For a two-dimensional array you need two indices to select an element
  • For a three-dimensional array you need three indices to select an element


PHP - Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).

First, take a look at the following table:

NameStockSold
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like this:

$cars = array (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
);

Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column.

To get access to the elements of the $cars array we must point to the two indices (row and column):

Example

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".
";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".
";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".
";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".
";
?>

Try it Yourself »

We can also put a for loop inside another for loop to get the elements of the $cars array (we still have to point to the two indices):

Example

for ($row = 0; $row < 4; $row++) {
  echo "

Row number $row

";
  echo "
    ";
      for ($col = 0; $col < 3; $col++) {
        echo "
  • ".$cars[$row][$col]."
  • ";
      }
      echo "
";
}
?>

Try it Yourself »


Complete PHP Array Reference

For a complete reference of all array functions, go to our complete PHP Array Reference.

The reference contains a brief description, and examples of use, for each function!



It really isn't clear from the code you've posted what your starting array structure or desired finished array structure should be.

At a guess, you can do the following:

$array = array();
$array['key1'] = 'one';
$array['key2'] = 'two';

print_r($array);
/*
array(
    'key1' => 'one',
    'key2' => 'two', …

Jump to Post

Array push can add a value (of any type) to an existing array.

array_push($array, $new_array);

If you want to assign values to a specific array index, you need to do it explicitly.
$array['my_index'] = $new_array;
Or
$array['my_index'][] = $new_array;

Jump to Post

Try just using:
$array['my_index'] = $new_array;

Jump to Post

All 10 Replies

Php add to multidimensional array

blocblue 238 Posting Pro in Training Featured Poster

9 Years Ago

It really isn't clear from the code you've posted what your starting array structure or desired finished array structure should be.

At a guess, you can do the following:

$array = array();
$array['key1'] = 'one';
$array['key2'] = 'two';

print_r($array);
/*
array(
    'key1' => 'one',
    'key2' => 'two',
)
*/

If that's incorrect, what exactly are you trying to achieve?

Php add to multidimensional array

9 Years Ago

THe reason of this is I wanna try to add elements in a 2 dimensional array by assigning a key index then use array_push()

Php add to multidimensional array

blocblue 238 Posting Pro in Training Featured Poster

9 Years Ago

Array push can add a value (of any type) to an existing array.

array_push($array, $new_array);

If you want to assign values to a specific array index, you need to do it explicitly.
$array['my_index'] = $new_array;
Or
$array['my_index'][] = $new_array;

Php add to multidimensional array

9 Years Ago

mr blocblue

does the blank square brackets is the container of the $new_array or not

Php add to multidimensional array

blocblue 238 Posting Pro in Training Featured Poster

9 Years Ago

Try just using:
$array['my_index'] = $new_array;

Php add to multidimensional array

9 Years Ago

two ways of adding values to an array
by specific index (string|int)

$array = array();
$array['key1'] = $val1;
$array['key2'] = $val2;
print_r($array);
/*
array(
    "key1"=>$val1,
    "key2"=>$val2
)
echo array["key1"] // prints $val1
*/

adding values by "push" uses next available int

$array = array();
$array[] = $val1;
$array[] = $val2;
print_r($array);
/*
array(
    0=>val1,
    1=>val2
)
echo array[0] // prints $val1
*/

multidimensional array

$array = array();
$array[0][] = $val1;
$array[0][] = $val2;
$array[] = array($val3, $val4);
print_r($array);
/*
array(
    0=>array(
        0=>$val1
        1=>$val2
    ),
    1=>array(
        0=>$val3
        1=>$val4
    )
)
echo array[0] // prints $val1
*/

Edited 9 Years Ago by jstfsklh211

Php add to multidimensional array

7 Years Ago

$array = array();
$array[0][] = $val1;
$array[0][] = $val2;
$array[] = array($val3, $val4);
print_r($array);

echo array[0] // prints $val1

Php add to multidimensional array

jkon 535 Posting Whiz in Training Featured Poster

7 Years Ago

Edited 7 Years Ago by jkon

Php add to multidimensional array

6 Years Ago

 
 

Php add to multidimensional array

diafol

6 Years Ago

This thread has become totally unravelled. The precise intent (what type of keys) has not been made clear. Please can we stop posting here as it's becoming a dump for who-knows-what. Thanks.

Edited 6 Years Ago by diafol

Reply to this topic

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.

How do you add a multidimensional array?

Creating Multidimensional Arrays You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.

Is multidimensional array PHP?

A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

How do you loop through a multidimensional array in PHP?

Looping through multidimensional arrays Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. To do this, you need to create nested foreach loops — that is, one loop inside another: The outer loop reads each element in the top-level array.

How can we store multidimensional array in database using PHP?

PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is represented by row * column. ... PHP Multidimensional Array Example..