John
John

Reputation: 1015

Issue formatting JSON array in PHP

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?

Upvotes: 0

Views: 45

Answers (3)

Sudhanshu Aggarwal
Sudhanshu Aggarwal

Reputation: 21

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;

Upvotes: 0

William Carneiro
William Carneiro

Reputation: 360

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"
];

Upvotes: 2

EinLinuus
EinLinuus

Reputation: 675

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'
];

Upvotes: 2

Related Questions