Chriser
Chriser

Reputation: 177

Create associative array from an associative array of objects

I have a problem converting variables into an array.

I am running a foreach loop to get values from my multidimensional array $images which contains the image name, e.g.: "Item Blue.png" or "Item Light Oak.png" and an id of each image.

foreach ($images['images'] as $image) {
  $image_name = explode(" ", substr_replace($image->filename ,"",-4));
  if (!empty($image_name[2])) {
    $colour = ucfirst($image_name[1] . " " . $image_name[2]);
  }
  else {
    $colour = ucfirst($image_name[1]);
  }
}

$colour variable is giving me Color name and $image->id can give me image id.

I would like to build $colors array with above variables so that it would look like this:

$colors = array(
    'Blue' => 1620,
    'Green' => 1467,
);

Kind of like this:

$colors = array(
    '$colour' => $image->id,
);

I have no idea how to do this and I will appreciate any help to give me at least some directions.

Upvotes: 0

Views: 2716

Answers (2)

mickmackusa
mickmackusa

Reputation: 48070

I fear the intention to use colours as keys may be unwise because data collisions will result in lost data in the result array.

Instead use the ids as keys and store the colour as values.

sscanf() is a direct way to isolate the colour string. %*s will match (but not capture the first word in the input string. %[^.] will capture the following non-dot characters.

Code: (Demo)

$result = [];
foreach ($images['images'] as $id => $obj) {
    sscanf($obj->filename, '%*s %[^.]', $colour);
    $result[$id] = ucfirst($colour);
}
var_export($result);

Upvotes: 0

Tad Bumcrot
Tad Bumcrot

Reputation: 351

This should be pretty straightforward ... Two things to do:

First initialize the colors array outside of your foreach:

 $colors=array();   //<-- add this
 foreach ($images['images'] as $image) {
     $image_name = explode(" ", substr_replace($image->filename ,"",-4));
     ...

then just add one line after the if/else, still inside your foreach loop that will insert a new item into the $colors array.

    ...
    else {
        $colour = ucfirst($image_name[1]);
    }
    $colors[$colour]=$image->id;  //<-- add this
}

This will create a colors array with contents like what you're looking for. I'm assuming that there is an 'id' key in the $image iterator. Did you need to create one?

All that said, you're not checking for these problems:

  1. color names with spaces, like 'light oak'
  2. item names with spaces like 'large item light oak.png'
  3. duplicate colors with different IDs

Hope that helps

Upvotes: 1

Related Questions