php - 如何在PHP中动态创建对象数组

标签 php arrays object

我想用 {a,b,c,d} 创建对象并有一个这个对象的数组:

[{1,1,3,5},{3,1,7,7},{3,5,7,1}]

值 a b c 和 d 在 lopp 中生成

我怎样才能创建那个对象?以及如何将对象添加到我的数组中?

最佳答案

无法像在 JavaScript 或其他语言中那样在 PHP 中编写对象字面量。

在 PHP 中最简单的方法是使用 type casting

// associative array
$arr = ["a" => 1, "b" => 2, "c" => 3, "d" => 4];

// cast as object
$obj = (object) $arr;

// Or you could do it all in one line
$obj = (object) ["a" => 1, "b" => 2, "c" => 3, "d" => 4];

一探究竟
echo $obj->a; // 1
echo $obj->b; // 2
echo $obj->c; // 3
echo $obj->d; // 4
echo json_encode($obj); // {"a":1,"b":2,"c":3,"d":4}

你的循环可能看起来像这样
$objects = [];
for ($i=0; $i<4; $i++) {
  // i'll just makeup some values for a,b,c,d here since i don't know
  // how you are assigning them
  $objects[] = (object) [
    "a" => $i,
    "b" => $i * 2,
    "c" => $i * $i,
    "d" => rand()
  ];
}
print_r($objects);

输出
Array
(
    [0] => stdClass Object
        (
            [a] => 0
            [b] => 0
            [c] => 0
            [d] => 102971157
        )

    [1] => stdClass Object
        (
            [a] => 1
            [b] => 2
            [c] => 1
            [d] => 167903564
        )

    [2] => stdClass Object
        (
            [a] => 2
            [b] => 4
            [c] => 4
            [d] => 1894248447
        )

    [3] => stdClass Object
        (
            [a] => 3
            [b] => 6
            [c] => 9
            [d] => 929037839
        )

)

和 JSON 输出
[
  {"a":0,"b":0,"c":0,"d":102971157},
  {"a":1,"b":2,"c":1,"d":167903564},
  {"a":2,"b":4,"c":4,"d":1894248447},
  {"a":3,"b":6,"c":9,"d":929037839}
]

编辑

how I could order my array by attribute b?



首先创建两个可重用的比较器
function ascendingComparator($a, $b) {
  if ($a > $b)      return 1;
  else if ($a < $b) return -1;
  else              return 0;
}

function descendingComparator($a, $b) {
  return -1 * ascendingComparator($a, $b);
}

然后使用 usort通过 b属性到比较器
// sort ascending; lowest b value will be first in the array
usort($objects, function($x, $y) {
  return ascendingComparator($x->b, $y->b);
});
echo json_encode($objects);

// OR sort descending; highest b value will be first in the array
usort($objects, function($x, $y) {
  return descendingComparator($x->b, $y->b);
});
echo json_encode($objects);

关于php - 如何在PHP中动态创建对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37954031/

相关文章:

c# - 将 PHP 脚本转换为 C#

javascript - 根据值对 javascript 中的对象键进行排序

java - Rhino - 将 javascript 对象传递给 java

php - 在 PHP 中剪切 UTF8 文本

php - fetchAll() 没有结果;

php - fatal error : Call to undefined function mysqli_result()

javascript - 计算字符串中的唯一单词

java - MATLAB:从 MATLAB 获取单元格数组到 Java

c - 二进制算法 C 编程

jquery - 将包含对象的 div 复制到另一个 div