我有一个小问题,我似乎无法轻易解决。修复可能很容易,但我太菜鸟了,无法自己修复。也许你们可以对此有所了解。
问题
我需要在 PHP 中创建一个多维数组。这工作得很好。但是,最后一个嵌套数组有时包含 2 个元素,有时包含 3 个元素。因此,本文标题中的“不对称”。
该问题很可能是由基于我的 PHP 代码中的开关变量创建嵌套数组引起的。当未定义变量时($button
例如case 'inactive'
),键无论如何都会放在$elements
数组中,但没有值。
PHP 代码
$player = Array();
$data = @$_POST['players'];
if (!empty($data) && is_array($data)) {
foreach($data as $id){
$player_info = mysqli_query($connection, "SELECT * FROM players WHERE id = '$id'");
$player_info = mysqli_fetch_assoc($player_info);
switch ($player_info['status']) {
case 'active':
$color = '#30B490';
$status = 'active';
$button = 'buttons';
break;
case 'inactive':
$color = '#A1A1A1';
$status = 'inactive';
break;
case 'standby':
$color = '#F0AD4E';
$status = 'standby';
$button = 'buttons';
break;
default:
$color = '#4FA1D9';
$status = 'unknown';
break;
}
// THIS PART SEEMS TO CAUSE MY ISSUE
$elements = array(
"indicator" => $color,
"status" => $status,
"button" => $button
);
// THIS PART SEEMS TO CAUSE MY ISSUE
foreach ($elements as $label => $element) {
$player[$id][$label] = $element;
}
}
}
print_r($player);
print_r() 结果
目前
Array (
[1] => Array (
[indicator] => #A1A1A1
[status] => inactive
[button] =>
)
[2] => Array (
[indicator] => #30B490
[status] => active
[button] => yes
)
[3] => Array (
[indicator] => #4FA1D9
[status] => standby
[button] => yes
)
)
它应该是什么
Array (
[1] => Array (
[indicator] => #A1A1A1
[status] => inactive
)
[2] => Array (
[indicator] => #30B490
[status] => active
[button] => yes
)
[3] => Array (
[indicator] => #4FA1D9
[status] => standby
[button] => yes
)
)
您可以看到 2 个结果之间的差异。看[button] =>
。当我 json_encode() 整个多维数组时,结果显示一个null
看起来不正确的值。
{"1":{"indicator":"#A1A1A1","status":"inactive","button":null},"2":{"indicator":"#30B490","status":"active","button":"buttons"},"3":{"indicator":"#4FA1D9","status":"unknown","button":"buttons"}}
我想要什么
我希望多维数组是干净的(没有空值),如“应该是什么”print_r()
结果中所示。
知道我应该在我的 PHP 代码中编辑什么以创建正确的多维数组吗?
最好的问候, Peter de Leeuw