php 用于创建对象的 for 循环不起作用
php for loop for creating objects doesnt work
我有这个代码
for ($x = 0; $x <= count($testas); $x += 2) {
$object = new stdClass();
$object->$testas[0] = $x;
$newArr[] = $object;
}
echo json_encode($newArr);
这里一切正常,但如果我像这样更改 $testas 数组:
for ($x = 0; $x <= count($testas); $x += 2) {
$object = new stdClass();
$object->$testas[$x] = $x;
$newArr[] = $object;
}
echo json_encode($newArr);
它没有打印出任何东西。请帮忙
谢谢
看起来是你想要的。奇数元素成为属性,事件元素成为键值对象的值。这些对象在一个数组中。
我最好将可变对象字段名称用花括号括起来。只是不要被它搞砸了。
$testas = array ('a', 'b', 'c', 'd');
$newArr = array();
for ($x = 0; $x < count($testas); $x += 2) {
$object = new stdClass();
$object->{$testas[$x]} = $testas[$x + 1];
$newArr[] = $object;
}
echo json_encode($newArr);
输出为:
[{"a":"b"},{"c":"d"}]
我有这个代码
for ($x = 0; $x <= count($testas); $x += 2) {
$object = new stdClass();
$object->$testas[0] = $x;
$newArr[] = $object;
}
echo json_encode($newArr);
这里一切正常,但如果我像这样更改 $testas 数组:
for ($x = 0; $x <= count($testas); $x += 2) {
$object = new stdClass();
$object->$testas[$x] = $x;
$newArr[] = $object;
}
echo json_encode($newArr);
它没有打印出任何东西。请帮忙
谢谢
看起来是你想要的。奇数元素成为属性,事件元素成为键值对象的值。这些对象在一个数组中。
我最好将可变对象字段名称用花括号括起来。只是不要被它搞砸了。
$testas = array ('a', 'b', 'c', 'd');
$newArr = array();
for ($x = 0; $x < count($testas); $x += 2) {
$object = new stdClass();
$object->{$testas[$x]} = $testas[$x + 1];
$newArr[] = $object;
}
echo json_encode($newArr);
输出为:
[{"a":"b"},{"c":"d"}]