我已经生成了一个“master”数组,看起来有点像这样:
Array ( [userID] => 152 [email] => xxxxx@googlemail.com [name] => Jay jay go go [stream] => 616 )
Array ( [userID] => 133 [email] => damxxxxian@indigo.com [name] => Damian T [stream] => 616 )
Array ( [userID] => 154 [email] => julie@indigo.com [name] => Julie1000 E [stream] => 615 [PROGRAMME] => Designer )
Array ( [userID] => 153 [email] => jay@indigo.com [name] => James1000 G [stream] => 616 [PROGRAMME] => Apple Develpepr )
这是循环到单个数组的输出,因此这4个数组中的每一个都有0到3的键。
我的问题是我希望创建一个表来保存所有这些数据,每行代表一个用户,但数组键可能略有不同。例如,前两个用户没有“程序”数组键/值,但我希望有一个列说“程序”但是对于那些在数组中没有这个的用户来说是空的。
希望这是有道理的。
答案 0 :(得分:2)
这可以通过将所有这些数组合并到一个数组中来实现。循环遍历数组中的每个项目,收集键(in_array可能会有帮助)。循环遍历您的键阵列以打印出表中的所有列标题,然后当您的脚本需要输出数组时,您可以简单地在每个人的循环中运行,在映射到列时循环遍历每个属性。这有点抽象,但我认为你可以填补其余部分。祝你好运!
答案 1 :(得分:1)
您可以列出要包含在表格中的列,然后为每个用户使用isset检查每列是否有值:
$columnNames = array('userID', 'email', 'name', 'stream', 'PROGRAMME');
foreach ($users as $user) {
echo '<tr>';
foreach ($columnNames as $columnName) {
echo '<td>';
if (isset($user[$columnName])) {
echo htmlspecialchars($user[$columnName]);
}
echo '</td>';
}
echo '</tr>';
}
答案 2 :(得分:1)
如果我没有弄错你的问题,通过这样做,你可以创建具有最大数组键的新数组;
$data = array(
array('userID' => 152, 'email' => 'xxxxx@googlemail.com', 'name' => 'Jay jay go go', 'stream' => 616),
array('userID' => 133, 'email' => 'damxxxxian@indigo.com', 'name' => 'Damian T', 'stream' => 616),
array('userID' => 154, 'email' => 'julie@indigo.com', 'name' => 'Julie1000 E', 'stream' => 615, 'PROGRAMME' => 'Designer'),
array('userID' => 153, 'email' => 'jay@indigo.com', 'name' => 'James1000 G', 'stream' => 616, 'PROGRAMME' => 'Apple Develpepr'),
);
$max_len = null;
$max_arr = null;
// First we find max array to grab its keys
foreach ($data as $i => $a) {
$len = count($a);
if ($max_len === null || $len > $max_len) {
$max_len = $len;
$max_arr = $data[$i];
}
}
$max_arr_keys = array_keys($max_arr);
$data_new = array();
foreach ($data as $i => $a) {
// and using max array keys here
foreach ($max_arr_keys as $k) {
// key exists? get value, or set as NULL
$data_new[$i][$k] = isset($a[$k]) ? $a[$k] : null;
}
}
print_r($data_new);
输出应该是这样的;
Array ( [userID] => 152 [email] => xxxxx@googlemail.com [name] => Jay jay go go [stream] => 616 [PROGRAMME] => null )
Array ( [userID] => 133 [email] => damxxxxian@indigo.com [name] => Damian T [stream] => 616 [PROGRAMME] => null )
Array ( [userID] => 154 [email] => julie@indigo.com [name] => Julie1000 E [stream] => 615 [PROGRAMME] => Designer )
Array ( [userID] => 153 [email] => jay@indigo.com [name] => James1000 G [stream] => 616 [PROGRAMME] => Apple Develpepr )