If I have an array of arrays and want to display them in a table, is there an efficient way to display them?
e.g.
Array
(
[0] => Array
(
[sku] => 1234
[upc] => 6-00000-01234-5
[measure_amount] => 30
[strength] => 100 mg
)
[1] => Array
(
[sku] => 5432
[upc] => 6-00000-05432-1
)
)
I'd like to output a table of all products but if the key doesn't exist just display a blank item. Right now, the only way I can think of doing this is iterate through every item, get the array_keys, combine them into a master key list and then use the key list to generate a table, but I think it would make more sense to do this:
Convert the above to:
Array
(
[0] => Array
(
[sku] => 1234
[upc] => 6-00000-01234-5
[measure_amount] => 30
[strength] => 100 mg
)
[1] => Array
(
[sku] => 5432
[upc] => 6-00000-05432-1
[measure_amount] =>
[strength] =>
)
)
I'm sure there's a better approach to this, like as I iterate through the list of items, merge the array with a model associative array... but I can't seem to get it to work.
答案 0 :(得分:1)
您可以将array_map与array_merge结合使用:
$data = [
['sku' => 1, 'upc' => 'foo', 'measure_amount' => 30, 'strength' => '100mg'],
['sku' => 2, 'upc' => 'bar'],
];
$clean = array_map(function ($entry) use ($complete_item) {
$all_keys = array_keys($complete_item);
$empty = array_combine($all_keys, array_fill(0, count($all_keys), ''));
return array_merge($empty, $entry);
},
$data
);
这将输出:
array(2) {
[0]=>
array(4) {
["sku"]=>
int(1)
["upc"]=>
string(3) "foo"
["measure_amount"]=>
int(30)
["strength"]=>
string(5) "100mg"
}
[1]=>
array(4) {
["sku"]=>
int(2)
["upc"]=>
string(3) "bar"
["measure_amount"]=>
string(0) ""
["strength"]=>
string(0) ""
}
}
答案 1 :(得分:1)
嗯...现在你的帖子很有意义,你有条目有随机字段,但你希望返回一个数组,每个元素都有相同的字段。这是蛮力的方式......我确信有一个功能,但我不确定..
$merge = array();
// Run the array for all the fields and put them in merge.
foreach($array1 as $val)
{
$merge = array_merge($merge,$val);
}
// Now run merge to set to a default...This probably has a function I don't use
foreach($merge as $key=>$val)
{
$merge[$key] = '';
}
// Now Use Merge to put it all back
foreach($array1 as $key=>$val)
{
$array1[$key] = array_merge($merge,$val);
}
// Your array1 now contains rows with all the same elements and in the same order.
答案 2 :(得分:1)
此解决方案适用于子阵列中的大量子阵列和/或大量元素,因为它不需要额外的内存来存储其他空元素:
现在,我能想到的唯一方法是迭代 每个项目,获取array_keys,将它们组合成一个主密钥列表 然后使用密钥列表生成一个表。
如果您事先不知道子阵列中的具体密钥,请使用此密钥收集所有可能的密钥:
foreach ($mainArray as $subArray) {
foreach ($subArray as $key=>$val) {
if (!isset($allKeys[$key])) {
$allKeys[$key] = '';
}
}
}
然后使用内部循环if (!isset($allKeys[$currentSubarrayKey]))
检查打印空表格单元格,因为isset
的工作速度比in_array
快得多。
答案 3 :(得分:0)
我建议使用您要创建的表的列创建第二个数组,而不是依赖于原始数组中的键。然后你可以这样循环:
$columns = array("sku","upc","measure_amount","strength");
foreach($mainArray as $a)
{
foreach($columns as $col)
{
//Access the array element like this: $a[$col]
}
}
注意:这只有在您事先知道密钥的情况下才有效。