Mapping the key value in assoc array base on its union?

你说的曾经没有我的故事 提交于 2019-12-25 03:56:12

问题


Array mapping?

I have

$A= array("A1"=>array("x"=>1,"b"=>2,"d"=>3,"s"=>8),
          "A2"=>array("a"=>4,"b"=>3,"c"=>2,"d"=>1)
          );

OUTPUT(HTML):

   | a |  b  |  c | d | x | s
------------------------------
A1 | 0 |  2  |  0 | 3 | 1 | 8
A2 | 4 |  3  |  2 | 1 | 0 | 0

Anyone know how to do this ?


回答1:


Retrieve the keys

$keys = array_unique(array_merge (array_keys($A['A1']), array_keys($A['A2'])));

Then create the output

echo " | ";
echo implode(' | ', $keys) . "\n";

echo "\n";
foreach ($A as $name => $oneA) {
  echo "$name ";
  foreach ($keys as $key) echo "| ". (isset($oneA[$key]) ? $oneA[$key] : 0);
  echo "\n";
}

or as html-table

<table>
  <tr>
    <td>&nbsp;</td>
    <td><?php implode('</td><td>', $keys);</td>
  </tr>
  <?php foreach ($A as $name => $oneA) : ?>
  <tr>
    <td><?php echo $name; ?></td>
    <?php foreach ($keys as $key): ?>
      <td><?php echo isset($oneA[$key]) ? $oneA[$key] : 0; ?></td>
    <?php endforeach; ?>
  </tr>
  <?php endforeach; ?>
</table>

You may sort the keys before and format the output. Its just the short form.




回答2:


First, collect all the keys in the inner arrays:

$keys = array_keys(
    array_reduce($A, function ($a, $b) { return $a + $b; }, array()));
sort($keys);

The print the headers, and finally iterate over the lines and, for each line, over the keys:

foreach ($A as $lineKey => $lineValue) {
    //TODO: print $lineKey;
    foreach ($keys as $k) {
        //TODO: print $lineValue[$k]; or 0
    }
}


来源:https://stackoverflow.com/questions/6466716/mapping-the-key-value-in-assoc-array-base-on-its-union

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!