1

im having some issues adding a new item to an associative array,

This is how i'm creating my structure:

$cpdata[$count] = array(
  'value' => $value->value,
  'images' => array(
    'color' => $value->color,
    'image' => $value->image,
  ),
);

and this is how it looks like when i output like a json:

{
  "value": "BOX",
  "images": {
    "color": "white",
    "image": "white.png"
  }
}

But i would like to add more items to images somthing like this:

{
  "value": "BOX",
  "images": [
    {
        "color": "white",
        "image": "white.png"
    },
    {
      "color": "black",
      "image": "black.png"
    },
    {
      "color": "gray",
      "image": "gray.png"
    }
  ]
}

I've tried with array_push and array_merge but i cant get it i've tried array_push($cpdata['images'][$count]['images'], 'color'=>'red', image' => 'red.png')

Could you please help me? Regards Mario

mxr10
  • 11
  • 3

2 Answers2

0

In context of PHP, what you have there is a JSON variable. If that is coming to you as a string you'll have to decode it first using json_decode($string);

Then you can set up an object, populate it with the image variables and write it back to the $json object as an array, like:

<?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);

After that you can push to it like

$newimage = new stdClass;
$newimage->color = "foo";
$newimage->image = "bar";
$json->images[] = $newimage;

output

print_r($json);

stdClass Object
(
    [value] => BOX
    [images] => Array
        (
            [0] => stdClass Object
                (
                    [color] => white
                    [image] => white.png
                )
            [1] => stdClass Object
                (
                    [color] => foo
                    [image] => bar
                )
        )
)

example https://www.tehplayground.com/oBS1SN1ze1DsVmIn

Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • Hi @Kinglish thank you for your help, but that data comes from a string var and after that i print it like a json, so i'm gonna try that if it works, thank you – mxr10 Jun 15 '21 at 01:13
  • @mxr10 - Did this help solve your question? If so, please accept as the answer. thanks – Kinglish Jun 15 '21 at 19:33
0

Before converting into 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']);
Indra Kumar S
  • 2,818
  • 2
  • 16
  • 27