Jonathan Ang
Jonathan Ang

Reputation: 31

WordPress PHP and Arrays for PHP to JSON encoding

I'm trying to follow a tutorial to do a JSON Schema via PHP. Here's the pseudo code:

$ArrayA = has URL[1], URL[2], URL[3] and so on
$ArrayB = has Page Title[1], Page Title[2], Page Title[3]

ArrayC[
        {
          '@type': "Person",
          'url': URL[1],
          'name': Page Title[1]
        },
        {
          '@type": "Person",
          "url": URL[2],
          "name": "Page Title[2]
        },
        {
          '@type': "Person",
          'url': URL[3],
          'name': Page Title[2]
        },
        {
          '@type': Person,
          'url': URL[4],
          'name': Page Title[4]
        },
      ],

Here's the actual code so far:

$casts = toolset_get_related_posts( get_the_ID(), 'stars-drama', array( 'query_by_role' => 'child', 'return' => 'post_object' ) );
foreach ($casts as $cast) {
$posttitles = $cast->post_title;
$casturl = get_permalink( $cast );
$actor = array(
        '@type' => "Person",
        'url'   => $casturl,
        'name'  => $posttitles
        )
}

Here, I was hoping $actor looks like ArrayC, but the output looks like only one page is entered while the rest are replaced when the foreach loop runs.

If I don't have the $actor array and just print_r($posttitles) and print_r($casturl) within the foreach loop, I get PostTitle[1]URL[1] PostTitle[2]URL[2] and so on. I'm not sure how to work with these to get the desired ArrayC form.

Thanks!

Upvotes: 0

Views: 203

Answers (1)

Jonathan Ang
Jonathan Ang

Reputation: 31

Resolved!

All I needed to do is to:

$casts = toolset_get_related_posts( get_the_ID(), 'stars-drama', array( 'query_by_role' => 'child', 'return' => 'post_object' ) );
foreach ($casts as $cast) {
$posttitles = $cast->post_title;
$casturl = get_permalink( $cast );
$actor = array(
        '@type' => "Person",
        'url'   => $casturl,
        'name'  => $posttitles
        )
$allactors[] =$actor;
}

Add another Array and use $allactors[] =$actor I suppose after each loop it will add each new array into $allactors without erasing the variables of the items.

Upvotes: 1

Related Questions