Adding an array to an array in PHP functions

I created a function in PHP that calls a web service and parses the result, evaluating the values ​​in the variables and returning them as an array. It all works fine, but it occurred to me to have an “array in my array”

I assign values ​​as shown below:

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

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

return $productArray;

However, now I have a piece of data that returns with several results, so I need to have an additional array to store them, I get the values ​​from the returned XML using the foreach loop, however I want to be able to add them to the array with the name so that I can refer to them in the returned data, this is where I have the problem ...

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

I tried to create an array for them using the code below:

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

And then, at the end, combining them:

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

, :

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

Array , , , PHP :

$productName = $functionReturnedValues['productName']; 

, :

$bestForArray = $functionReturnedValues['bestForArray']; 

, -

+3
1

$productArray['bestForArray'] = $bestForArray;

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

, !

+3

Source: https://habr.com/ru/post/1740130/


All Articles