Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have created a function in PHP that calls a webservice and parses through the result, assinging values to variables and returning them all as an Array. This all works perfectly, however I have come across a need to have an "array within my array"

I am assigning values as below:

$productName = $product->Name;
$productID = $product->ID;

$productArray = array(
            'productName' => "$productName",
            'productID' => "$productID"
            );

return $productArray;

However I now have a piece of data that comes back with multiple results so I need to have a additional array to store these, I am getting the values from the returned XML using a foreach loop, however I want to be able to add them to the array with a name so I can reference them in the returned data, this is where I have a problem...

$bestForLists = $product->BestFors;
        foreach( $bestForLists as $bestForList )
        {  
            $productBestFors = $bestForList->BestFor; 
            foreach( $productBestFors as $productBestFor )
                {
                    $productBestForName = $productBestFor->Name;
                    $productBestForID = $productBestFor->ID;
                }
        }

I tried creating an array for these using the below code:

$bestForArray[] = (array(
                "productBestForID" => "$productBestForID",
                "productBestForName" => "$productBestForName"
                ));

And then at the end merging these together:

$productArray= array_merge($productArray,$bestForArray);

If I print out the returned value I get:

Array ( [productName] => Test Product [productID] => 14128 [0] => Array ( [productBestForID] => 56647 [productBestForName] => Lighting ) [1] => Array ( [productBestForID] => 56648 [productBestForName] => Sound ) )            

I would like to give the internal Array a name so I can reference it in my code, or is there a better way of doing this, at the moment I am using the following in my PHP page to get values:

$productName = $functionReturnedValues['productName']; 

I would like to use the following to access the array I could then loop through:

$bestForArray = $functionReturnedValues['bestForArray']; 

Hope someone can help

share|improve this question

1 Answer

up vote 3 down vote accepted

you could write

$productArray['bestForArray'] = $bestForArray;

instead of

$productArray= array_merge($productArray,$bestForArray);

Tell me if this does the trick ! Jerome Wagner

share|improve this answer
Perfect, didn't think it would be that easy! Thanks – bateman_ap Apr 7 '10 at 10:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.