Home Ask Login Register

Developers Planet

Your answer is one click away!

Packy February 2016

Append array with variable

So what I am doing is creating a function that will pass in what array to append to another array. Here is what I am "trying" to do:

Global $shirts;
Global $prices;

$shirts = array(
        'Option1' => array(),
        'Option2' => array(),
    );

$prices = array(
        'product1' => array(
                        'bronze' => 1, 
                        'silver' => 2, 
                        'gold' => 3,
                       ),
        'product2' => array(
                        'bronze' => 4, 
                        'silver' => 5, 
                        'gold' => 6,
                       ),  
    );


function shirts($shirts_model) {

        global $shirts;
        global $prices;

        foreach ($shirts => $shirt) {

            $result = array_merge($shirt, $prices[$shirt_model]);

        }
         print_r($result);  

    }

shirts('product2');

so now the $shirts array would now look like:

$shirts = array(
            'Option1' => array(
                            'bronze' => 4, 
                            'silver' => 5, 
                            'gold' => 6,
                           ),
            'Option2' => array(
                            'bronze' => 4, 
                            'silver' => 5, 
                            'gold' => 6,
                           ),
        );

with the "product2" array. Basically now I could call the shirts(); function and pass in any option to append that options array to the shirts array. But this approach is not working? I am getting a white screen and I dont think this is working.

Hope that made sense.

Answers


Gavriel February 2016

function shirts($shirt_model) {
    global $shirts;
    global $prices;

    // create an empty array for the results
    $results = array();

    // loop so that you have both the key, value, and we'll only use the key
    foreach ($shirts as $option => $shirt) {
        // just add the prices to the results
        $results[$option] = $prices[$shirt_model]);
    }
    return $results;  
}


devpro February 2016

As I mentioned in comments now I am convert it into answer.

First of all you need to fix your foreach() function as:

foreach($array as $value)

Modified code:

function shirts($shirts_model) 
{ 
    global $shirts, $prices; 

    foreach ($shirts as $key => $shirt) 
    { 
        $result[$key] = $prices[$shirts_model];
    } 
    return $result;
}

Now calling it:

$record = shirts('product2');
echo "<pre>";
print_r($record);

Error Reporting:

Add error_reporting ON in your code this will help you to find out the issue.

error_reporting();

Post Status

Asked in February 2016
Viewed 3,524 times
Voted 11
Answered 2 times

Search




Leave an answer


Quote of the day: live life