0

I am using

I want to create a new key to add auction details to a product.

<?php
        //Enter your code here, enjoy!
$resArr = array();
array_push($resArr, array("product" => "test1", "category" => "cat1"));
array_push($resArr, array("product" => "test2", "category" => "cat2"));
array_push($resArr, array("product" => "test3", "category" => "cat3"));

array_push($resArr[0]["auction"], array("name" => "auct1", "price" => "1"));

    
print_r($resArr);

// wanted result with array_push
$wantedArr = array(
    array(
        "product" => "test1", 
        "category" => "cat1",
        "auction" => array("name" => "auct1", "price" => "1")
    ),
    array(
        "product" => "test2", 
        "category" => "cat2",
        "auction" => array("name" => "auct1", "price" => "1")
    ),
    array(
        "product" => "test3", 
        "category" => "cat3",
        "auction" => array("name" => "auct1", "price" => "1")
    ),
);
print_r($wantedArr);


I would like to have the following array:

Array
(
    [0] => Array
        (
            [product] => test1
            [category] => cat1
            [auction] => Array
                (
                    [name] => auct1
                    [price] => 1
                )

        )

    [1] => Array
        (
            [product] => test2
            [category] => cat2
            [auction] => Array
                (
                    [name] => auct1
                    [price] => 1
                )

        )

    [2] => Array
        (
            [product] => test3
            [category] => cat3
            [auction] => Array
                (
                    [name] => auct1
                    [price] => 1
                )

        )

)

Any suggestions what I am doing wrong?

1
  • You should be getting an error: array_push() expects parameter 1 to be array, null given Commented Sep 12, 2021 at 16:28

1 Answer 1

2

You are not adding to the auction as an array, you are just setting it to an array. So...

$resArr[0]["auction"] = array("name" => "auct1", "price" => "1");

gives...

[0] => Array
    (
        [product] => test1
        [category] => cat1
        [auction] => Array
            (
                [name] => auct1
                [price] => 1
            )

    )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.