Question:
PHP: Assign elements to a two dimensional array?
jumpingrightin
2011-07-24 04:38:26 UTC
For example, I have part number and description in PHP.

How do I assign the value $part_number and $description to a two dimensional array in a while loop?

$inventory_item[][] = $part_number . $description
That won't work...

So how do I assign $part_number to the first array (on the left) and $description to the second array (on the right)? Thanks!
Four answers:
anonymous
2011-07-24 05:00:01 UTC
I think Associative Array should be used instead of two-d array.



In associative array, each ID key is associated with a value.



When storing data about specific named values, a numerical array is not always the best way to do it.



With associative arrays we can use the values as keys and assign values to them.



The ID keys can be used in a script:




$ages['Peter'] = "32";

$ages['Quagmire'] = "30";

$ages['Joe'] = "34";



echo "Peter is " . $ages['Peter'] . " years old.";

?>

The code above will output:



Peter is 32 years old.



Similarly you can use $part_number as id which returns $description as a value.



Your code should be something like this:



$inventory_item[$part_number] = $description
anonymous
2016-12-30 11:20:38 UTC
Php 2 Dimensional Array
Erika
2016-11-12 04:20:54 UTC
Php Two Dimensional Array
OddParity
2011-07-24 04:49:32 UTC
I think you misunderstand what a two-dimensional array is. Think of an array with dimensions [x][y] as a table that has x columns and y rows. So you end up with x*y fields. Now, what you need is a table with two columns and as many rows as you have number-description-pairs. So you should either have a two-dimensional array with one dimension being two or (and this is easier and more logical) two one-dimensional arrays. To assign a value to the right place in the array, you need indexes. The index should be 0 in the beginning and then be counted up in the while-loop. So for example:



$part_number_array[];

$description_array[];

$index=0;



while(...whatever your while-condition is...){

$part_number_array[$index] = $part_number;

$description_array[$index] = $description;

$index++; // --> $index = $index + 1;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...