Manthan Dave
Manthan Dave

Reputation: 2157

How to pass looping through multidimentional array into function

Hi Currently i am working with some multidimentional array operations with looping.

Actually i have to pass multidimentional array to function and in that function i need whole array data.

But issue here is i am getting only single item of array not all items of array in function.

Below the code which i have try :

foreach($sp_data as $sp_product_data) // this loop is for another purpose
                {

                  $sp_product_details = (array)$sp_product_data;
                  $product_links = array(array(
                  'sku' => $gp_sku,
                  'link_type' => 'associated',
                  'linked_product_sku' => $sp_product_details['sku'], 
                  'linked_product_type' => 'simple',
                  'position' => '1',    
                  )
                ); 
             echo "<pre>";
            print_r(product_links); //When i am printing the data its shows me all array items

        $this->testproduct($product_links); // but when i am pass the data to function and in that function when i displayed data its gives only first array item
                }

My function :

function testproduct($product_links)
{
echo "<pre>";
print_r($product_links);
}

In function i am getting only first item of array. Please help what i am missing

Upvotes: 0

Views: 61

Answers (2)

NewUser
NewUser

Reputation: 13333

Use array_push for this So the code should be like this

$custom_product_data = array();
foreach($sp_data as $sp_product_data) {
  $sp_product_details = (array)$sp_product_data;
  $product_links = array(
      'sku' => $gp_sku,
      'link_type' => 'associated',
      'linked_product_sku' => $sp_product_details['sku'], 
      'linked_product_type' => 'simple',
      'position' => '1',    
  ); 

    if( is_array($product_links) ) {
      array_push($custom_product_data, $product_links);
    }
  }

  $this->testproduct($custom_product_data); 

NOTE

Don't forget to use testproduct function outside the loop. Otherwise it will not give you result.

Upvotes: 1

Shaniawan
Shaniawan

Reputation: 243

For showing whole array you have to do this Use this format

$product_links[]=array(
              'sku' => $gp_sku,
              'link_type' => 'associated',
              'linked_product_sku' => $sp_product_details['sku'], 
              'linked_product_type' => 'simple',
              'position' => '1',    
                );
}#end of foreach loop
#now call the testproduct function. THis line must be outside the loop

$this->testproduct($product_links); 

Upvotes: 1

Related Questions