ammu
ammu

Reputation: 117

how to change the datas from horizontal key,values to vertical

How to change the data from horizontal key, values to vertical.

For example:

$array = array( 
  "100" => array("1" => 1000, "2" => 2000), 
  "101" => array("1" => 350, "2" => 500), 
  "102" => array("1" => 1000, "2" => 2000), 
  "103" => array("1" => 10),
  "104" => array("2" => 5) 
);


/* Output:

id   key1  key2
100  1000  2000
101   350   500
102  1000  2000
103    10     0
104     0     5

*/

Upvotes: 0

Views: 803

Answers (2)

CodeManX
CodeManX

Reputation: 11855

Straight-forward formatting with hardcoded indices for the nested array:

$array = array( 
  "100" => array("1" => 1000, "2" => 2000), 
  "101" => array("1" => 350, "2" => 500), 
  "102" => array("1" => 1000, "2" => 2000), 
  "103" => array("1" => 10),
  "104" => array("2" => 5) 
);

function get_key(&$array, $key, $default=0) {
  if (isset($array[$key])) {
    return $array[$key];
  } else {
    return $default;
  }
}

$format = "%5s %5s %5s";
echo sprintf($format, "id", "key1", "key2");
foreach ($array as $key => $value) {
  echo sprintf($format, $key, get_key($value, "1"), get_key($value, "2"));
}

Upvotes: 0

Alma Do
Alma Do

Reputation: 37365

This certainly may be resolved in easy way with some single foreach loop, but I prefer more common solution:

//data:
$array = array( 
  "100" => array("1" => 1000, "2" => 2000), 
  "101" => array("1" => 350, "2" => 500), 
  "102" => array("1" => 1000, "2" => 2000), 
  "103" => array("1" => 10),
  "104" => array("2" => 5) 
);

//definitions: formats and values
$default = 0;
$title   = ['id', 'key1', 'key2'];
$rowText = "%s\t%s\t%s";


//result string
$keys    = array_unique(call_user_func_array('array_merge', array_map('array_keys', $array)));
sort($keys);
$result  = call_user_func_array('sprintf', array_merge([$rowText], $title));
foreach($array as $key=>$row)
{
   $result .= PHP_EOL.call_user_func_array(
      'sprintf', 
      array_merge(
         [$rowText],
         [$key], 
         array_map(function($x) use ($default, $row)
         {
            return isset($row[$x])?$row[$x]:$default;
         }, $keys)
      )
   );
}

So result will look like:

id      key1    key2
100     1000    2000
101     350     500
102     1000    2000
103     10      0
104     0       5

Upvotes: 1

Related Questions