0

The structure which I want to get:

[
        {
            id: 'some id',
            name: 'Name',
        },
        {
            id: 'some id',
            name: 'Name',
        }, 
        // more arrays
]

and here is how I get the data

$students = get_posts( $args )

foreach ( $students as $student ) {
     $id = $student->ID;
     $name = $student->post_title;
}

now how can I convert the above data to the structure I want? thanks

6
  • Your desired output is actually an array of objects... Commented Jan 17, 2020 at 20:38
  • we have an object [] and bunch of arrays {}, no? Commented Jan 17, 2020 at 20:40
  • no, {} is an object, and [] is an array Commented Jan 17, 2020 at 20:40
  • I'm assuming the output is JSON, so even if you create it as an array then they will be encoded as objects. Commented Jan 17, 2020 at 20:45
  • @Nick is this just php or in js {} is object too? Commented Jan 17, 2020 at 20:47

1 Answer 1

1

Your output is not a valid PHP structure, but I'm assuming you meant you want the equivalent as a PHP array.

//create empty array to add subarrays to
$array = array();

//loop through values
foreach (get_posts($args) as $student) {

     //add subarray to array. using `[]` this way means "add to next sequential array key"
    $array[] = array(
        'id' => $student->ID, 
        'name' => $student->post_title
    );
}
Sign up to request clarification or add additional context in comments.

Comments

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.