pixeloft pixeloft - 4 months ago 13
JSON Question

PHP insert element between elements in an array

I have PHP code that spits out a dynamic JSON array like this:

{"key":"user_email","relation":"=","value":"email@gmail.com"},
{"key":"user_email","relation":"=","value":"email@gmail.com"},
{"key":"user_email","relation":"=","value":"email@gmail.com"}


I need to adjust it to insert an element between each element like so:

{"key":"user_email","relation":"=","value":"email@gmail.com"},
{"operator":"OR"},
{"key":"user_email","relation":"=","value":"email@gmail.com"},
{"operator":"OR"},
{"key":"user_email","relation":"=","value":"email@gmail.com"}


This is my current PHP code that generates the JSON:

$jsonData = array();

$allStaffInit = mysql_query("SELECT * FROM users");

while ($staffrow = mysql_fetch_object($allStaffInit)){

$object = new stdClass();
$object->key = "user_email";
$object->relation = "=";
$object->value = $staffrow->value;

$jsonData[] = $object;
}

Answer

You can create the separator object before your while loop.

$or = (object) ['operator' => 'OR'];

Then add it to the array in your loop after you add $object.

while ($staffrow = mysql_fetch_object($allStaffInit)){
    $object = new stdClass();
    $object->key = "user_email";
    $object->relation = "=";
    $object->value = $staffrow->value;
    $jsonData[] = $object;
    $jsonData[] = $or;      // << here
}

Before you json_encode, pop off the extra one after the last item.

array_pop($jsonData);