1

What would be the equivalent PHP array structure to create an object with identical properties:

For example... create the object 'columns' below in PHP using json_encode:

jQuery('#example').dataTable( {
  "ajaxSource": "sources/objects.txt",
  "columns": [
    { "data": "engine" },
    { "data": "browser" },
    { "data": "platform" },
    { "data": "version" },
    { "data": "grade" }
  ]
} );

(I am trying to build a dynamic datatable and define the columns in the source JSON.

2
  • why not simply json_decode(YOUR_JSON); ? Commented Feb 19, 2016 at 15:30
  • I am using json_decode... but I'm not sure of how to create the structure in PHP that json_decode will output with that structure. Commented Feb 19, 2016 at 16:08

1 Answer 1

1

You could use an ArrayObject

new ArrayObject([
 "ajaxSource" => "...",
  "columns" => [
    new ArrayObject(['data' => 'engine']),
    new ArrayObject(['data' => 'browser']),
    new ArrayObject(['data' => 'etc'])
  ]
]);

if you want to assemble this you need to store the objects inside an array like

$columns = [];
for(...) {
$columns[] = new ArrayObject(['data' => 'etc']);
}

Have a look at http://php.net/manual/de/arrayobject.construct.php

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure I understand... If I do the following: $object = new ArrayObject(["title"=>"x"]); $object = new ArrayObject(["title"=>"y"]); $object = new ArrayObject(["title"=>"z"]); The result is just: { "title": "z" }
@FishBulbX you need use $object[] instead of $object. Without [], you just assign a bunch of value into $object, of course the last value will override everything prior. With [], php will recognize this is an array, and add new values into the tail of the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.