【问题标题】:Add another item to array associative in php在php中向数组关联添加另一个项目
【发布时间】:2021-08-30 20:09:52
【问题描述】:

我在向关联数组添加新项目时遇到了一些问题,

这就是我创建结构的方式:

$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_pusharray_merge,但我无法得到它 我试过array_push($cpdata['images'][$count]['images'], 'color'=>'red', image' => 'red.png')

你能帮帮我吗? 问候 马里奥

【问题讨论】:

    标签: php arrays associative-array array-push


    【解决方案1】:

    在 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
                    )
            )
    )
    

    示例https://www.tehplayground.com/oBS1SN1ze1DsVmIn

    【讨论】:

    • 嗨@Kinglish谢谢你的帮助,但是数据来自一个字符串var,然后我像json一样打印它,所以如果它有效,我会尝试,谢谢跨度>
    • @mxr10 - 这有助于解决您的问题吗?如果是这样,请接受作为答案。谢谢
    【解决方案2】:

    转成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']);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 2012-10-11
      • 2015-10-30
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多