More efficient way to set PHP variables over and over again - php

I am curious of a better way of doing the code I have below, I find it repetitive and would like to cut down on it, any suggestions?
I was trying to do something with Variable Variables but I failed at getting that to work.
So basically I have a bunch of color names that I get with $_GET[color-name-here']
The goal is to set a color's code to a new color's code. So using the URL I am able to set the code for the color red to the color code of green so red's value would become 00FF00
// Get color and color replacement values from URL
// get_value_or is ran through this code...
// isset($_GET[$key]) && !empty($_GET[$key]) ? $_GET[$key] : $default;
$red = get_value_or('red', null);
$orange = get_value_or('orange', null);
$yellow = get_value_or('yellow', null);
$green = get_value_or('green', null);
$turquoise = get_value_or('turquise', null);
$blue = get_value_or('blue', null);
$purple = get_value_or('purple', null);
$pink = get_value_or('pink', null);
$white = get_value_or('white', null);
// Define Default Color Name and Hexcode values
$colorsArray = array(
'red' => 'FF0000',
'orange' => 'FF5000',
'yellow' => 'FFF200',
'green' => '00FF00',
'turquoise' => '00F0C8',
'blue' => '0064FF',
'purple' => '9F00FF',
'pink' => 'FF0082',
'white' => 'FFFFFF'
);
// Iterate Color Array and Set New Color Values if they exist
foreach($colorsArray as $colorName => $colorCode){
// Do something to set each color Name with a New color code, if that color name has a value set
}
// Right now I am doing it manually for each color name, all 9+ like this...
//Set Reds NEW color value
if(isset($red)){
$colorsArray['red'] = $colorsArray[$red];
}
//Set oranges NEW color value
if(isset($orange)){
$colorsArray['orange'] = $colorsArray[$orange];
}
//Set yellows NEW color value
if(isset($yellow)){
$colorsArray['yellow'] = $colorsArray[$yellow];
}
So any ideas how to set all the colors with less code?
A color's code should ONLY be updated if that color has a NEW value set in the URL using $_GET variables
PS) I wasn't sure of a good title for this question, feel free to change it if you have a better one, thanks

If I were you, I would put the assignments in the loop:
$colorsArray = array(
'red' => 'FF0000',
'orange' => 'FF5000',
'yellow' => 'FFF200',
'green' => '00FF00',
'turquoise' => '00F0C8',
'blue' => '0064FF',
'purple' => '9F00FF',
'pink' => 'FF0082',
'white' => 'FFFFFF'
);
foreach ($colorsArray as $colorName => $colorCode) {
$colorsArray[$colorName] = get_value_or($colorName, $colorCode);
}
It's quite neat, but I'm not sure whether it works with your real code or not.
Edit
I updated the code because I realized that the array $color_names was unnecessary, you have them in the keys of $colorsArray.
Edit
Updated the code again because the if in the loop was unnecessary too.

You can access all global variables by using the super global $GLOBALS. So you could do this:
foreach ($colorsArray as $colorName => $colorCode) {
if (isset($GLOBALS[$colorName]) {
$colorsArray[$colorName] = $GLOBALS[$colorName];
}
}
More info about $GLOBALS.

Related

PHP Spreadsheet color not working

I am trying to apply collors to my cells using a function which is this:
function color($cell, $color, $find = true){
if ($find){
$color = $this->color_helper($color);
}
$this->sheet->getStyle($cell)->getFill()->applyFromArray(array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'startcolor' => array(
'rgb' => $color
)
));
}
colors are defined in the color_picker function and they return something like ''FF0000'for red.
Now the problem is, after I download the file, nothing is changed, its like the original file.

Converting 8 Bit Images to 16 bit with Php ImageMagick

What I'm trying to do is convert an 8 bit image to a 16 bit image using php ImageMagick. With Imagick it's as easy as convert /location/image.jpg -colors 8 -depth 16 txt:-. In the PHP docs it shows that you can do it using $imagick->setImageDepth(16); but the problem is that it doesn't give you the 16 bit hex / rgb numbers.
Is there an advantage to using 16 bit when trying to extract colors from an image? If not then I'm wondering isn't the php function working?
Here is what I get from $mapColor->getColor():
Array
(
[r] => 51
[g] => 51
[b] => 51
[a] => 1
)
Array
Here is my code for getting colors:
// Create new instance
$imagick = new Imagick($image);
// Set number of colors
$numberColors = 6;
// Set colorspace
$colorSpace = Imagick::COLORSPACE_SRGB;
// Set tree depth
$treeDepth = 0;
// Set dither
$dither = false;
// Convert to 16 bit
$imagick->setImageDepth(16);
// Quantize image to number of colors
$imagick->quantizeImage($numberColors, $colorSpace, $treeDepth, $dither, false);
// Get Image Dimensions
$sizes = $imagick->getImageGeometry();
// Get image's histogram
$pixels = $imagick->getImageHistogram();
// Temp cache dimensions
$totalSize = $sizes['width'] * $sizes['height'];
// Loop through each pixel
foreach($pixels as $k => $v) {
// Get total number of color instances
$count = $v->getColorCount();
// Get colormap at pixel
$mapColor = $imagick->getImageColormapColor($k);
// Get colore
$rgbColor = $mapColor->getColor();
// Convert to RGB hex values
$red = str_pad(dechex($rgbColor['r']), 2, 0, STR_PAD_LEFT);
$green = str_pad(dechex($rgbColor['g']), 2, 0, STR_PAD_LEFT);
$blue = str_pad(dechex($rgbColor['b']), 2, 0, STR_PAD_LEFT);
// Set hexadecimal
$hex = $red.$green.$blue;
// Calculate color percentage
$percentage = (100 * $count) / $totalSize;
// Push colors into array
$colors[] = array(
'red' => $rgbColor['r'],
'green' => $rgbColor['g'],
'blue' => $rgbColor['b'],
'hex' => $hex,
'count' => $count,
'percentage' => $percentage,
);
}
print_r($colors);

Filtering out multiple records in dataset

I'm working with a dataset coming back from a very complex view with multiple subselects and joins against several tables in a very large and convoluted database.
Each record has a structure like this:
MainValue = XXTS10, qtyPlaceholder1, qtyPlaceholder2, qtyPlaceholder3..., actualQty = 3, qtyPlaceholderKey = 1, color = blue.
MainValue = XXTS10, qtyPlaceholder1, qtyPlaceholder2, qtyPlaceholder3..., actualQty = 10, qtyPlaceholderKey = 3, color = blue.
MainValue = XXTS10, qtyPlaceholder1, qtyPlaceholder2, qtyPlaceholder3..., actualQty = 9, qtyPlaceholderKey = 2, color = blue.
So for each color and MainValue values, there are multiple records. I need to set the value of each qtyPlaceholder based on the actualQty where the qtyPlaceholderKey will tell me what value to put in each and derive only one record out of many so that the final single record looks like this:
MainValue = XXTS10, qtyPlaceholder1 = 3, qtyPlaceholder2 = 9, qtyPlaceholder3 = 10, color = blue.
I know I've done this hundreds of times over the years, but I'm just having mental block creating the proper looping structure and conditionals to create a single record out of many with the values mapped to the placeholders correctly. Trying to accomplish this in PHP, but it may be a good idea to reexamine the view and see if it can be adjusted, but I really don't want to go down that path if I can help it.
Any suggestions?
You can do this in SQL using conditional aggregation. Here is a select form of the query:
select MainValue,
max(case when qtyPlaceholderKey = 1 then actualQty end) as qtyPlaceholder1,
max(case when qtyPlaceholderKey = 2 then actualQty end) as qtyPlaceholder2,
max(case when qtyPlaceholderKey = 3 then actualQty end) as qtyPlaceholder3,
color
from complexview v
group by MainValue, color;
Loop through your array and create a new array indexed by
MainValue
color
qtyPlaceholderKey with a value of actualValue
Then 'flatten' the new array by looping through the new array and assigning key value pairs for MainValue, color and all qtyPlaceholderKeys and their corresponding actualValues.
$dbrows = array(
array(
'MainValue' => 'XXTS10',
'actualQty' => 3,
'qtyPlaceholderKey' => 1,
'color' => 'blue',
),
array(
'MainValue' => 'XXTS10',
'actualQty' => 9,
'qtyPlaceholderKey' => 2,
'color' => 'blue',
),
array(
'MainValue' => 'XXTS10',
'actualQty' => 10,
'qtyPlaceholderKey' => 3,
'color' => 'blue',
),
);
$values = array();
foreach($dbrows as $r) {
$values[$r['MainValue']][$r['color']][$r['qtyPlaceholderKey']] = $r['actualQty'];
}
$result = array();
foreach($values as $mainValue => $colorValues) {
foreach($colorValues as $color => $qtyPlaceholderValues) {
$row = array('MainValue' => $mainValue, 'color' => $color);
foreach($qtyPlaceholderValues as $qtyPlaceholderKey => $actualQty) {
$row["qtyPlaceholderKey$qtyPlaceholderKey"] = $actualQty;
}
$result[] = $row;
}
}
print_r($result);
Demo

Using supplier with largest margin using PHP logic

I have the following values from a database call that I want to apply some logic to. I thought I could originally use PHP's max however this doesn't appear to be the case.
I have three suppliers of a product. They might not all stock the item I am displaying, and they all offer a different margin, on a product by product basis though, so that is why I can't just say generally supplier 1 is better than supplier 2 etc.
$supplier1Live = 1
$supplier2Live = 1
$supplier3Live = 0
$marginSupplier1 = 20
$marginSupplier2 = 40
$martinSupplier3 = 50
In this example I would want to use Supplier 2 as they stock the product supplier2Live = 1 and also have the better margin than the other supplier who stocks the product (supplier1)
My mind however is drawing a complete blank in how to code this?
I thought I could add it to an array giving:
$array = array(
"supplier1" => array(
"live" => 1,
"margin" => 20
),
"supplier2" => array(
"live" => 1,
"margin" => 40
),
"supplier3" => array(
"live" => 0,
"margin" => 50
)
);
And run something on that, but not sure what to.
Filter the array using array_filter (filter by live==1), and then find the maximum out of the resultant array (maximum on the "margin" value)
Like this, if I understand correctly
$array = array(
"supplier1" => array(
"live" => 1,
"margin" => 20
),
"supplier2" => array(
"live" => 1,
"margin" => 40
),
"supplier3" => array(
"live" => 0,
"margin" => 50
)
);
$res = array_filter($array,function($v){return $v["live"];});
$supplier = array_reduce($res, function($a, $b){
return $a["margin"]>$b["margin"]?$a:$b;
});
print_r($supplier);
Try something like this:
$best_supplier = null;
$best_supplier_margin = null;
foreach($array as $name => $supplier) {
if($supplier['live']) {
if($supplier['margin'] > $best_supplier_margin || is_null($best_supplier_margin)) {
$best_supplier = $name;
$best_supplier_margin = $supplier['margin'];
}
}
}
if(is_null($best_supplier)) throw new Exception('No suppliers are live!');
echo $best_supplier;
So you basically want to find the max of supplierXLive * marginSupplierX?
You can also implement a custom compare function and provide it to PHPs usort() function

Initializing array shared values at once

Maybe this isn't possible, I've never seen it myself, but thought I'd ask. If this is my array,
$myarr = array(
'red' => 7,
'green' => 7,
'blue' => 18,
'cyan' => 14,
'pink' => 18
'brown' => 18
);
is there a way while initializing the array to set similar values at once? like
'red' && 'green' =>7,
'blue' && 'pink' && 'brown' => 18,
'cyan' =>14
of course I'm not expecting this syntax to work but is there something that gets me the same idea?
PHP Manual does not provide description of any way to do that. BTW, you may initialize values in the following way:
$myarr['red'] = $myarr['green'] = 7;
$myarr['blue'] = $myarr['pink'] = $myarr['brown'] = 18;
$myarr['cyan'] = 14;
It isn't possible and, honestly, I fail to see a situation it could be useful if the repeated values are in the same array.
Would you like to provide an example, in order for me to get it?
A fun aside:
$bibi = array (
'foo' == 'bar' => 2,
);
$bubu = array (
'foo' && 'bar' => 2,
);
Both this syntaxes actually evaluate the expressions on the left. As in, in 2 is assigned to $bibi[0] and $bubu[1].

Categories