我在向关联数组添加新项目时遇到一些问题,
这就是我创建结构的方式:
$cpdata[$count] = array(
'value' => $value->value,
'images' => array(
'color' => $value->color,
'image' => $value->image,
),
);
这就是我输出 json 时的样子:
{
"value": "BOX",
"images": {
"color": "white",
"image": "white.png"
}
}
但是我想添加更多项目到
images
这样的东西:
{
"value": "BOX",
"images": [
{
"color": "white",
"image": "white.png"
},
{
"color": "black",
"image": "black.png"
},
{
"color": "gray",
"image": "gray.png"
}
]
}
我尝试过
array_push
和 array_merge
但我无法得到它
我试过了array_push($cpdata['images'][$count]['images'], 'color'=>'red', image' => 'red.png')
你能帮我一下吗? 问候 马里奥
在 PHP 上下文中,您拥有的是 JSON 变量。如果这是一个字符串,您必须首先使用
json_decode($string);
对其进行解码
然后您可以设置一个对象,用图像变量填充它并将其作为数组写回
$json
对象,例如:
<?php
// example code
$json = <<<EOT
{
"value": "BOX",
"images": {
"color": "white",
"image": "white.png"
}
}
EOT;
$json = json_decode($json);
$i = new stdClass;
$i->color = $json->images->color;
$i->image = $json->images->image;
$json->images = array($i);
之后你可以像这样推动它
$newimage = new stdClass;
$newimage->color = "foo";
$newimage->image = "bar";
$json->images[] = $newimage;
输出
print_r($json);
stdClass Object
(
[value] => BOX
[images] => Array
(
[0] => stdClass Object
(
[color] => white
[image] => white.png
)
[1] => stdClass Object
(
[color] => foo
[image] => bar
)
)
)
转换成json之前
$cpdata[$count] = array(
'value' => $value->value,
'images' => array(
'color' => $value->color,
'image' => $value->image,
),
);
// Cpdata array has $count which has `images` as an array and we want to push another element(array) into images array
array_push($cpdata[$count]['images'], ['color'=>'red', 'image' => 'red.png']);
向“images”数组添加更多项目,您应该将其初始化为数组,然后使用 [ ] 追加新项目。
$cpdata[$count]['images'][]
本质上是将一个新的关联数组附加到与$count
数组中索引$cpdata
处的元素关联的“图像”数组
// Assuming $value is an object with properties value, color, and image
$value = (object) array('value' => 'BOX', 'color' => 'white', 'image' => 'white.png');
$cpdata = array();
$count = 0;
$cpdata[$count] = array(
'value' => $value->value,
'images' => array(
array('color' => $value->color, 'image' => $value->image)
),
);
// Adding more items to the "images" array
$cpdata[$count]['images'][] = array('color' => 'black', 'image' => 'black.png');
$cpdata[$count]['images'][] = array('color' => 'gray', 'image' => 'gray.png');
// Print the result as JSON
echo json_encode($cpdata, JSON_PRETTY_PRINT);
JSON_PRETTY_PRINT
是一个以人类可读的方式使用 JSON 输出的标志