0

Essentially I have the following conditionals that are made to assemble an array - the issue is the array it currently creating has too many objects.

$a = 1
$b = 2


if ($a == 1)){
$results[]['id'] = 5;
$results[]['reasons'] = "A issue";
}

if ($b == 1){
$results[]['id'] = 6;
$results[]['reasons'] = "B issue";
}

if ($b == 2){
$results[]['id'] = 6;
$results[]['reasons'] = "B issue";
}
)

$json = json_encode(array($results));
echo $json;

Current Result:

[
  {
    "id": 5
  },
  {
    "reasons": "A issue"
  },
  {
    "id": 6
  },
  {
    "reasons": "B issue"
  }
]

What I need:

[
  {
    "id": 5,
     "reasons": "A issue"
  },
  {
    "id": 6,
     "reasons": "B issue"
  }
]

How can this JSON Array be built correctly using the conditionals?

1
  • This may just be an example, but you should also try and combine and conditions that always generate the same JSON ($b is 1 or 2) to reduce duplication of code if you can. Commented Mar 9, 2021 at 7:41

3 Answers 3

2

You use $results[][$value] which means push something to an array.

All you have to do is put the $id and the $reason in an array and push that array to your results, not each item individually:

$results[] = [
   'id' => 5,
   'message' => 'A issue'
];
Sign up to request clarification or add additional context in comments.

Comments

2

You must add one object of array to your array to do that. You're actually adding strings and numbers.

CHANGE:

$results[]['id'] = 5;
$results[]['reasons'] = "A issue";

TO:

$results[] = [
    'id' => 5,
    'reasons' => "A issue"
];

Comments

0

You can write this code like this:

$a = 1;
$b = 2;


if ($a == 1){
$results[] = ['id'=> 5, 'reasons' => 'A issue'];

}

if ($b == 1){
$results[] =['id'=> 6, 'reasons' => 'B issue'];

}

if ($b == 2){
$results[] =['id'=> 6, 'reasons' => 'B issue'];

}


$json = json_encode($results);
echo $json;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.