Faisal Naseer
Faisal Naseer

Reputation: 4248

Selecting data vertically from multidimensional arrays in php

In my project I am collecting information about products.the data structure I have in a multi dimensional array consists of productName,quantity,price,subtotal arrays. I want to select data from each of these rows vertically to collect sets of product related data.

Right now: I got using print_r($product_data)

Array(
        [productname] => Array ( [0] => 7 [1] => 8 ) 
        [quantity] => Array ([0] => 23 [1] => 22 ) 
        [price] => Array ( [0] => 2 [1] => 2 ) 
        [subtotal] => Array ( [0] => 46 [1] => 44 )
    )

Desired:

 Array(
        Array('p_id'=>7,'quantity'=>23,'unitPrice'=>2,'subTotal'=>46)
        Array('p_id'=>8,'quantity'=>22,'unitPrice'=>2'subTotal'=>44)
    )

and can anybody suggest a better title for this post? thanks in advance

Upvotes: 2

Views: 104

Answers (2)

Kostas Mitsarakis
Kostas Mitsarakis

Reputation: 4747

You need two foreach loops to access all the values of your original table and to construct the new table:

$data = array (
    'productname'=>array(0=>7, 1=>8),
    'quantity'=>array(0=>23, 1=>22),
    'price'=>array(0=>2, 1=>2),
    'subtotal'=>array(0=>46, 1=>44),
);
$result = array();

foreach($data as $key => $value) {
    foreach($value as $s_key => $s_value) {
        $result[$s_key][$key] = $s_value;
    }
}
var_dump($result);

Result:

array (size=2)
  0 => 
    array (size=4)
      'productname' => int 7
      'quantity' => int 23
      'price' => int 2
      'subtotal' => int 46
  1 => 
    array (size=4)
      'productname' => int 8
      'quantity' => int 22
      'price' => int 2
      'subtotal' => int 44

Upvotes: 2

Standej
Standej

Reputation: 753

I would try it like this

foreach($your_array as $key=>$element){
    foreach($element as $subkey=>$subelement){
         $result[$subkey][$key] = $subelement;
    }
}

Like this i think you will get array you need.

Upvotes: 0

Related Questions