【问题标题】:Create an object of arrays in PHP在 PHP 中创建一个数组对象
【发布时间】:2020-01-17 20:33:41
【问题描述】:

我想得到的结构:

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

这是我获取数据的方式

$students = get_posts( $args )

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

现在如何将上述数据转换为我想要的结构? 谢谢

【问题讨论】:

  • 你想要的输出实际上是一个对象数组...
  • 我们有一个对象 [] 和一堆数组 {},不是吗?
  • 不,{} 是一个对象,[] 是一个数组
  • 我假设输出是 JSON,所以即使你将它创建为一个数组,它们也会被编码为对象。
  • @Nick 这只是 php 还是 js 中的 {} 也是对象?

标签: php arrays object


【解决方案1】:

你的输出不是一个有效的 PHP 结构,但我假设你的意思是你想要一个 PHP 数组的等价物。

//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
    );
}

【讨论】:

    猜你喜欢
    • 2012-01-17
    • 2023-03-07
    • 2021-03-30
    • 2011-04-08
    • 2014-06-03
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    相关资源
    最近更新 更多