简体   繁体   中英

Populating Multi-Dimensional Array

I'm playing around with multi-dimensional arrays. I'm trying to figure out how to populate an element/object of an array of an array of an array.

I simplified what I am ultimately trying to do with just an example on cars but this mimics the array structure I am going for minus more complexity.

Please excuse me if this is too obvious or stupid of a question.

It's returning an error and I can't populate: array_push() expects parameter 1 to be array, null given

If first parameter has to be an array, how can I populate an element of some array?

EDIT: I think I figured out that I can accomplish what I want by $arr[0][0][0] = 100; BUT not by array_push(); So my question and what I'm wondering now is what the heck array_push() is supposed to be used for?

<!-- Array
(
[0] => Array
    (
        [0] => Array // Brand (Mercedes)
            (
                [0] => 100 // Quantity
                [1] => 50000 // Price
                [2] => Germany // Nationality
                [3] => 1926 // Year Founded
                [4] => Mercedes
            )

        [1] => Array // Brand (BMW)
            (
                [0] => 200 // Quantity
                [1] => 20000 // Price
                [2] => Japan // Nationality
                [3] => 1933 // Year Founded
                [4] => Nissan
            )
    )

) -->

<?php

$arr = array(array(array()));


array_push($arr[0][0][0], 100);
array_push($arr[0][0][1], 50000);
array_push($arr[0][0][2], Germany);
array_push($arr[0][0][3], 1926);
array_push($arr[0][0][4], Mercedes);

array_push($arr[0][1][0], 200);
array_push($arr[0][1][1], 20000);
array_push($arr[0][1][2], Japan);
array_push($arr[0][1][3], 1933);
array_push($arr[0][1][4], Nissan);


echo "<pre>";
print_r($arr);

?>

You don't need array_push .

You just need this: $arr[0][0][0] = 100;

PHP doesn't have multi-dimensional arrays, it has arrays of arrays.

You may try this

<?php

$arr = [];


$arr[0][0][0] = 100;
$arr[0][0][1] = 50000;
$arr[0][0][2] = "Germany";
$arr[0][0][3] = 1926;
$arr[0][0][4] = "Mercedes";

$arr[0][1][0] = 200;
$arr[0][1][1] = 20000;
$arr[0][1][2] = "Japan";
$arr[0][1][3] = 1933;
$arr[0][1][4] = "Nissan";


?>

array_push works as $array[] = "a" , but it is more used to push multiple values into an array.

If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function. quoted from php.net

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