Adding an Array inside an array in a PHP function
- by bateman_ap
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