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

Answers


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

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.


Need Your Help

htmlspecialchars utf-8 returns empty string

php mysql utf-8 htmlspecialchars

I'm doing a .php RSS generator and I have a problem trying to get data from my database in this line:

How to fulfill custom view in fragment

android android-fragments

I am developing an app with 2 custom view in top and bottom of fragment layout. But when I add 2 fragment , they are not fill the parent layout,