I have a problem converting variables into array.
I am running foreach loop to get values from my multidimensional array $images. $images array contains image name eg: "Item Blue.png" or "Item Light Oak.png" and 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 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.
Thanks
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:
color names with spaces, like 'light oak'
item names with spaces like 'large item light oak.png'
duplicate colors with different IDs
Hope that helps
Related
I want to access to 'image'
I reached my array 'questions' with this $file = $request->files->get('quiz')['questions'];
but I can't go further
Can you help me please
Based on your screen shot you could,
$image = $request->files->get('quiz')['questions'][0]['image'];
Each nested level is an array so you can walk all the way down using the array keys.
Note that [0] will be the first question, but you probably want all the questions. If so, you can loop over them.
foreach ($request->files->get('quiz')['questions'] as $question) {
$image = $question['image'];
//
}
The scalaire value on the get is depreciated now.
You can use the "all" :
foreach ($request->files->all('quiz')['questions'] as $question) {
$image = $question['image'];
}
I'm not even sure how to approach the problem so I'm just stating the problem. Any help is highly appreciated.
There's this array ($colors) of all possible values:
$colors = array ('red','blue','green','yellow');
Then there's an array ($boxes) of all the possible values - consisting of equal number of values as $colors:
$boxes = array ('circular','squared','hexagonal','triangular');
There's this third array which defines the constraints in making the unique combination:
$possible_combos = array
(
array('circular','red','blue'),
array('squared','red','green'),
array('hexagonal','blue','yellow'),
array('triangular','red','green')
);
Question: How do I get a new array $result with key=>value combinations just that each box is assigned a unique color out of it's possible sets of colors
So a valid $result array would be:
Array ( [circular] => red
[squared] => blue
[hexagonal]=> yellow
[triangular] => green
)
NOTE: If you traverse sequentially, 'red', 'blue', 'green' might get assigned to first three 'boxes' and there might not be anything to pick for the fourth box (since 'yellow' is not allowed to be assigned to it.
I'm thinking, to process the least occurring 'colors' first but really unsure how to handle it syntactically.
Once again thanks for looking into it, in advance! Even some help with how to approach the problem would be nice.
Following code is not producing the correct output either:
foreach ($colors as $c => $color) {
foreach ($boxes as $b => $box) {
for ($i=0; $i < count($colors) ; $i++) {
if(in_array($possible_combos[$i][1],$colors) && !in_array($possible_combos[$i][1], $result))
{
$result[$box] = $possible_combos[$i][1];
unset($colors[$c]);
break;
}
else if(in_array($possible_combos[$i][2],$colors) && !in_array($possible_combos[$i][2], $result))
{
$result[$box] = $possible_combos[$i][2];
unset($colors[$c]);
break;
}
}
}
}
I'm thinking, to process the least occurring 'colors' first but really unsure how to handle it syntactically.
That's a good intuition considering the fact that you have only one box type that can share one of many colors. Because your constraining resource is color, I think it makes sense to sort your rules by them first and then you can distribute by scarcity.
https://3v4l.org/u5pBK
$colors = array ('red','blue','green','yellow');
$boxes = array ('circular','squared','hexagonal','triangular');
$possible_combos = array
(
array('circular','red','blue'),
array('squared','red','green'),
array('hexagonal','blue','yellow'),
array('triangular','red','green')
);
// collect constraints ordered by rarest
foreach ($possible_combos as $constraint) {
$box = array_shift($constraint);
foreach ($constraint as $color) {
$constraints[$color] []= $box;
}
}
// assign rarest first to last
asort($constraints);
foreach ($constraints as $color => $allowedBoxes) {
foreach ($allowedBoxes as $box) {
$key = array_search($box, $boxes);
// if we have a match, then remove it from the collection
if ($key !== false) {
$result[$box] = $color;
unset($boxes[$key]);
continue 2;
}
}
}
print_r($result);
Array
(
[hexagonal] => yellow
[circular] => blue
[squared] => green
[triangular] => red
)
I have the following code that I am using on WordPress:
if($terms && !is_wp_error($terms) ) {
$colors = array();
foreach ($terms as $term) {
$colors[] = '\'' . $term->slug . '\'';
}
}
print_r(array_values($thePack));
The variable $color now is a basic Array, which print_r displays like this:
Array (
[0] => 'white'
[1] => 'green'
)
I'd like to make a condition in order recognize whether the array has or not a specific value, for example:
if(in_array('white', $colors) {
echo "This is white";
}
However, it is not working at all, because the in_array does not recognize the value in the array!
How could I make the condition work?
Your array values (the color names) include single quotes, which you need to include when you search for a value:
if(in_array("'white'", $colors) {
// ...
}
Why not do something like this:
while(list($key, $value) = each($array)){
if($value == 'white'){
echo 'this is white';
}
}
The problem is you are escaping the color into the array. Instead of using
$colors[] = '\''.$term->slug.'\''
Just do
$colors[] = $term->slug
And when you output the slug to the web page or the database, then you escape it.
Apologies in advance since I'm a PHP novice and I'm sure I'm not using the right terms here.
I am making an automated product data feed using a set of provided SKUs, but the feed requires separate entries for size and gender variation of the products.
Is there a simple way to take this:
$SKUs = array('Product1', 'Product2', 'Product3')
And "multiply" each entry in the array with these:
$gender = array('M', 'F');
$size = array('S', 'M', 'L', 'XL');
So that I end up with this result:
$feed = array('Product1M-S', 'Product1M-M', 'Product1M-L', 'Product1M-XL', 'Product1F-S'...)
$feed = array();
foreach ($SKUs as $sku) {
foreach ($gender as $g) {
foreach ($size as $s) {
$feed[] = $sku.$g.'-'.$s;
}
}
}
print_r($feed);
Maybe there exists a simple array function, but this one is easy to read, and ready for future "easy" changes.
PS. This is a great lecture with a similar problem: http://dannyherran.com/2011/06/finding-unique-array-combinations-with-php-permutations/
PS2. As KA_lin suggested, you can make a function to do this, however, I haven't got knowledge about the array and product structure, and don't know if i.e. the sizes are always the same (S, L, X) for each product. If the arrays are always the same, they can be hardcoded inside the function body as KA_lin suggested. I presented only a linear solution, but You can easily upgrade it too Your needs.
You just have to iterate through all 3 arrays at once and append to a new array like this:
$SKUs = array('Product1', 'Product2', 'Product3')
function generate_product_combinations($SKUs)
{
$size = array('S', 'M', 'L', 'XL');//these 2 arrays are universal
$gender = array('M', 'F'); //and can belong here rather than params
$final = array(); //but should be taken from a config
foreach($SKUs as $sku)
{
foreach($size as $size_shirt)
{
foreach($gender as $sex)
{
$final[]=$sku.$gender.'-'.$sex;
}
}
}
return $final;
}
$products = generate_product_combinations($SKUs);
I'm using SimpleXML to extract images from a public feed # Flickr. I want to put all pulled images into an array, which I've done:
$images = array();
foreach($channel->item as $item){
$url = $path->to->url;
$images[] = $url;
}
From this I can then echo out all the images using:
foreach($images as $image){
//output image
}
I then decided I wanted to have the image title as well as the user so I assumed I would use:
$images = array();
foreach($channel->item as $item){
$url = $path->to->url;
$title = $path->to->title;
$images[$title] = $url;
}
I thought this would mean by using $image['name of title'] I could output the URL for that title, but it gives an Illegal Offset Error when I run this.. and would only have the title and url, but not the user.
After Googling a bit I read you cannot use _ in the array key, but I tried using:
$normal = 'dddd';
$illegal = ' de___eee';
$li[$normal] = 'Normal';
$li[$illegal] = 'Illegal';
And this outputs right, ruling out _ is illegal in array keys (..I think).
So now I'm really confused why it won't run, when I've used print_r() when playing around I've noticed some SimpleXML objects in the array, which is why I assume this is giving an error.
The ideal output would be an array in the format:
$image = array( 0 => array('title'=>'title of image',
'user'=>'name of user',
'url' =>'url of image'),
1 => array(....)
);
But I'm really stumped how I'd form this from a foreach loop, links to reference as well as other questions (couldn't find any) are welcome.
$images = array();
foreach ($channel->item as $item){
$images[] = array(
'title' => $item->path->to->title,
'url' => $item->path->to->url
);
}
foreach ($images as $image) {
echo "Title: $image[title], URL: $image[url]\n";
}
Underscore is not forbidden symbol for array keys, the only problem you might run to, that titles some times overlap and you might loose some items in your array. Most correct way would be deceze example
If you prefer associative array you can use image path as array key and title as value.