Wednesday, 29 August 2018

PHP Create a multidimensional array for JSON output

I feel terrible even asking because I have been TRYING to understand and comprehend other peoples examples this is what i'm TRYING to accomplish

{
  "field": [
    {
      "appid": 0,
      "page": 0,
      "fieldname": "Sweet",
      "value": "Tammy Howell"
    },
    {
      "appid": 1,
      "page": 1,
      "fieldname": "Cecilia",
      "value": "Shana Jordan"
    },
    {
      "appid": 2,
      "page": 2,
      "fieldname": "Merritt",
      "value": "Copeland Pena"
    }
  ]
}

I need to be able to make the above JSON output happen when doing an SQL SELECT statement
Here is my currentCode
$x = 0;
$userFieldsResult = mysqli_query($database_id, "SELECT * FROM theDB.DynamicFields ORDER BY Page, Priority") or die (mysqli_error($database_id));

        if (mysqli_num_rows($userFieldsResult)<=0)
            {
                echo "nothing found";
                exit;
            } else
            {
                while($row = mysqli_fetch_array($userFieldsResult))
                {
                    $userFields[$x]['appid'] = $row['appid'];
                    $userFields[$x]['page'] = $row['page'];
                    $userFields[$x]['fieldname'] = $row['fieldname'];
                    $userFields[$x]['value'] = $row['value'];

                    $x++;
                }
                echo json_encode($userFields);
                exit;
            }

echo json_encode($userFields);

This is normally how i just been outputting json so they each are just part of 1 array looping, but I am trying to understand how to create more "in-depth" JSON arrays so they have a specific identifier before they list out the information.
  [
    {
      "appid": 0,
      "page": 0,
      "fieldname": "Sweet",
      "value": "Tammy Howell"
    },
    {
      "appid": 1,
      "page": 1,
      "fieldname": "Cecilia",
      "value": "Shana Jordan"
    },
    {
      "appid": 2,
      "page": 2,
      "fieldname": "Merritt",
      "value": "Copeland Pena"
    }
  ]

In my example I just want to be able to have "field" be the "upper" part of the array that holds all the information as i showed in the example above.

In this particular configuration, you are being returned an object with properties, of which, the property's value may be an array.
So what you should actually be doing is creating a stdClass object in PHP and assigning it a property of "field" which is an empty array. Then you can push into this array stack.
$obj = new stdClass();
$obj->fields = array();
while(....){
    $obj->fields[$x]['appid'] =
    $obj->fields[$x]['appid'] = $row['appid'];
    $obj->fields[$x]['page'] = $row['page'];
    $obj->fields[$x]['fieldname'] = $row['fieldname'];
    $obj->fields[$x]['value'] = $row['value'];
}

Now you can json encode the object and return it.
echo json_encode($obj);

0 comments:

Post a Comment