Vote count:
0
I have a small issue I can't seem to figure out easily. The fix is probably quite easy but I am too much of a noob to fix it myself. Perhaps you guys could shed some light on this.
I need to create a multidimensional array in PHP. This works just fine. However, the last nested array sometimes consists of 2 elements, other times of 3. Hence "asymmetrical" in the title of this post.
The issue is most likely caused by the creation of the nested array based on the switch variables in my PHP code. When a variable is not defined ($button in case 'inactive' for example), the key is put inside the $elements array anyway but without a value.
$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);
Currently
Array (
[1] => Array (
[indicator] => #A1A1A1
[status] => inactive
[button] =>
)
[2] => Array (
[indicator] => #30B490
[status] => active
[button] => yes
)
[3] => Array (
[indicator] => #4FA1D9
[status] => standby
[button] => yes
)
)
What it should be
Array (
[1] => Array (
[indicator] => #A1A1A1
[status] => inactive
)
[2] => Array (
[indicator] => #30B490
[status] => active
[button] => yes
)
[3] => Array (
[indicator] => #67967
[status] => standby
[button] => yes
)
)
You can see the difference between the 2 results. Look at [button] =>. When I json_encode() the entire multidimensional array the result shows a value null which just doesn't seem right.
{"1":{"indicator":"#A1A1A1","status":"inactive","button":null},"2":{"indicator":"#30B490","status":"active","button":"buttons"},"3":{"indicator":"#4FA1D9","status":"unknown","button":"buttons"}}
I would like the multidimensional array to be clean (without empty values) like shown in the "what is should be" print_r() result.
Create asymmetrical multidimensional array in PHP
Aucun commentaire:
Enregistrer un commentaire