【问题标题】:WordPress PHP and Arrays for PHP to JSON encodingWordPress PHP 和 PHP 到 JSON 编码的数组
【发布时间】:2020-01-02 17:34:28
【问题描述】:

我正在尝试按照教程通过 PHP 执行 JSON 架构。伪代码如下:

$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]
        },
      ],

这是目前为止的实际代码:

$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
        )
}

在这里,我希望 $actor 看起来像 ArrayC,但输出看起来像只输入一页,而当 foreach 循环运行时,其余的被替换。

如果我没有 $actor 数组,而在 foreach 循环中只有 print_r($posttitles) 和 print_r($casturl),我会得到 PostTitle[1]URL[1] PostTitle[2]URL[2] 和很快。我不确定如何使用这些来获得所需的 ArrayC 表单。

谢谢!

【问题讨论】:

    标签: php arrays wordpress


    【解决方案1】:

    已解决!

    我需要做的就是:

    $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;
    }
    

    添加另一个数组并使用 $allactors[] =$actor 我想在每个循环之后,它会将每个新数组添加到 $allactors 中,而不会删除项目的变量。

    【讨论】:

    • 永远不要让这样的错字获得= $array() 我建议总是用方括号初始化任何数组。并且不要忘记行尾的分号= [];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    相关资源
    最近更新 更多