I'm trying to replace the code below
$Palette = array(
"0"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"1"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"2"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"3"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"4"=>array("R"=>176,"G"=>46,"B"=>224,"Alpha"=>100),
);
with something similar but different values for the R, G and B. I have written the code below so far as a replacement:
$x = '0';
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
do
{
if ($correct == $incrementarray[$x])
{
$colour[$x] = '"'.$x.'"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),';
}
else
{
$colour[$x] = '"'.$x.'"=>array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100),';
}
$x++;
}
while ($x <= '4');
$allcolours = $colour[0].$colour[1].$colour[2].$colour[3].$colour[4];
however, when I implement it into my script using the line below , it doesn't work.
$Palette = array($allcolours);
$x = '0';
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
do
{
if ($correct == $incrementarray[$x])
{
$Pallete[$x] = array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100);
}
else
{
$Pallete[$x] = array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100);
}
$x++;
}
while ($x <= '4');
there is a little excessive usage of $x.
as a matter of fact, you don't need that variable at all
$Palette = array();
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
foreach ($incrementarray as $value)
{
if ($correct == $value)
{
$Palette[] = array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100);
}
else
{
$Palette[] = array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100);
}
}
you need to create array, not the PHP code to create array.
Related
I got two nested index arrays, which I want to populate with values using a function.
But on a conditional basis: if this, populate the first array; if that, populate the second array.
Here is what I got:
WORKING, but repetitive
$sectionCounter = 0;
foreach($sections as $section) {
if ($direction === 'up') {
$array1[$sectionCounter][] = 1;
$array1[$sectionCounter][] = 25;
// ...
} else {
$array2[$sectionCounter][] = 1;
$array2[$sectionCounter][] = 25;
// ...
}
$sectionCounter++;
}
PREFERRED (not working yet)
function addElements($temp, $sectionCounter) {
$temp[$sectionCounter][] = 1;
$temp[$sectionCounter][] = 25;
// ...
}
foreach($sections as $section) {
if ($direction === 'up') {
addElements($array1, $sectionCounter);
} else {
addElements($array2, $sectionCounter);
}
$sectionCounter++;
}
You can try another approach instead
$sectionCounter = 0;
$data = [
'up' => $array1,
'other' => $array2
];
foreach($sections as $section) {
$dir = $direction === 'up'? 'up': 'other';
$data[$dir][$sectionCounter][] = 1;
$data[$dir][$sectionCounter][] = 25;
// ...
$sectionCounter++;
}
$array1 = $data['up'];
$array2 = $data['other'];
Is there any way to optimize this code? I mean its working and all but it seems with lots of "elseif" its actually not so optimized:
foreach ($plenty_variation['properties'] as $row) {
if (strpos($row['relationValues']['0']['value'], $needle_de_0) === 0) {
$result_de_0 = $row['relationValues']['0']['value'];
$shopware["translations"]["0"]["customFields"]["free1"] = str_replace("Text_de_0_","",$result_de_0);
break;
}
elseif (strpos($row['relationValues']['1']['value'], $needle_de_0) === 0) {
$result_de_0 = $row['relationValues']['1']['value'];
$shopware["translations"]["0"]["customFields"]["free1"] = str_replace("Text_de_0_","",$result_de_0);
break;
}
elseif (strpos($row['relationValues']['2']['value'], $needle_de_0) === 0) {
$result_de_0 = $row['relationValues']['2']['value'];
$shopware["translations"]["0"]["customFields"]["free1"] = str_replace("Text_de_0_","",$result_de_0);
break;
}
}
In $row['relationValues']['0']['value'] the ['0'] is inconsistent and not always the same.
Why don't you use another loop?
foreach ($plenty_variation['properties'] as $row) {
for($i = 0; $i < count($row); $i++){
$value = $row['relationValues'][$i]['value'];
if(strpos($value, $needle_de_0) === 0){
$shopware["translations"][$i]["customFields"]["free" . $i] = str_replace("Text_de_0_", "", $value);
break;
}
}
}
In the case above I take that you'd like to loop the $shopware['translations'] positions as the same of the $plenty_variation['properties']. If this is not the case, just let it fixed:
$shopware["translations"]["0"]["customFields"]["free1"]
I update my code from PHP 5 to PHP 7 and i got problem with foreach loop. I loocked wor answers here, but none is working. Or i dont understand where i have problem
function getStructure($pid = 0, $expand = array(), $alevel = 0)
{
$struct = array();
if ( $alevel > $this->levelCount) $this->levelCount = (int)$alevel;
$str = $this->dbStructure->getStructure($pid);
foreach ($str as &$row)
{
if ($row["type"] == STRUCT_PAGE)
{
$row["editLink"] = "editPage";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_MODULE)
{
$row["editLink"] = "editModule";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_LINK)
{
$row["editLink"] = "editLink";
$row["target"] = "_blank";
}
elseif ($row["type"] == STRUCT_CATALOG)
{
$row["editLink"] = "editCatalog";
$row["target"] = "_self";
}
$row["childrens"] = $this->getStructure((int)$row["id"], $expand, $alevel+1);
if ($row["type"] == STRUCT_CATALOG and isset($row["childrens"][0]["shortcut"]))
{
$row["shortcut"] = $row["childrens"][0]["shortcut"];
$row["target"] = $row["childrens"][0]["type"] == STRUCT_LINK ? "_blank" : "_self";
}
$struct[] = $row;
}
unset($row);
return $struct;
}
All the time $struct is NULL and I need to be multidimensional array
This code by itself is good. Has no problems, only ampersand is not needet. The problem was in different place. Sorry for spam
I have array with show names like this:
$shows = array('morning_show_15_02_2014_part2.mp3',
'morning_show_15_02_2014_part1.mp3',
'morning_show_14_02_2014_part2.mp3',
'morning_show_14_02_2014_part1.mp3',
'morning_show_13_02_2014_part2.mp3',
'morning_show_13_02_2014_part1.mp3');
So the list look like:
morning_show_15_02_2014_part2.mp3
morning_show_15_02_2014_part1.mp3
morning_show_14_02_2014_part2.mp3
morning_show_14_02_2014_part1.mp3
morning_show_13_02_2014_part2.mp3
morning_show_13_02_2014_part1.mp3
This is what i get when i loop the directory.
But the list should look like this:
morning_show_15_02_2014_part1.mp3
morning_show_15_02_2014_part2.mp3
morning_show_14_02_2014_part1.mp3
morning_show_14_02_2014_part2.mp3
morning_show_13_02_2014_part1.mp3
morning_show_13_02_2014_part2.mp3
Still ordered by date, but part 1 is first and then comes part 2.
How can i get this list into right order?
Thank you for any help!
Resolved!
Code is prett nasty but i got what i was looking for:
public function getMp3ListAsJSONArray() {
$songs = array();
$mp3s = glob($this->files_path . '/*.mp3');
foreach ($mp3s as $key => $mp3Source) {
$mp3Source = basename($mp3Source);
$mp3Title = substr($mp3Source, 4);
$mp3Title = substr($mp3Title, 0, -4);
$mp3Title = basename($mp3Source, ".mp3");
$mp3Title = str_replace('_', ' ', $mp3Title);
$mp3Title = ucfirst($mp3Title);
$songs[$key]['title'] = $mp3Title;
$songs[$key]['mp3'] = urldecode($this->files_url . '/' . $mp3Source);
}
rsort($songs);
$pairCounter = 1;
$counter = 0;
foreach ($songs as $key => $value) {
$playlist[$pairCounter][] = $value;
$counter = $counter + 1;
if($counter == 2) {
$pairCounter = $pairCounter + 1;
$counter = 0;
}
}
foreach ($playlist as $show) {
$finalList[] = $show[1];
$finalList[] = $show[0];
}
$finalList = json_encode($finalList);
return $finalList;
}
Output is like i described in the topic.
Try to use array sort
Here is an example for you
http://techyline.com/php-sorting-array-with-unique-value/
You must definitely write your own string comparision function. Remember that you have 2 different comparisons. The first compares the first parts for the filenames as strings. The second part compares the numbers, where 20 comes after 2. This is a natural number sorting for the second part. The third part is after the last dot in the filename. This will be ignored.
<?php
function value_compare($a, $b) {
$result = 0;
$descending = TRUE;
$positionA = strpos($a, 'part');
$positionB = strpos($b, 'part');
if ($positionA === $positionB) {
$compareFirstPart = substr_compare($a, $b, 0, $positionA + 1);
if ($compareFirstPart === 0) {
$length = 0;
$offset = $positionA + strlen('part');
$positionDotA = strrpos($a, '.');
$positionDotB = strrpos($b, '.');
$part2A = '';
$part2B = '';
if ($positionDotA !== FALSE) {
$part2A = substr($a, $offset, $positionDotA);
} else {
$part2A = substr($a, $offset);
}
if ($positionDotB !== FALSE) {
$part2B = substr($b, $offset, $positionDotB);
} else {
$part2B = substr($b, $offset);
}
$result = strnatcmp($part2A, $part2B);
} else {
$result = $compareFirstPart;
if ($descending) {
$result = -$result;
}
}
}
return $result;
}
$shows = array('morning_show_15_02_2014_part2.mp3', 'morning_show_15_02_2014_part1.mp3', 'morning_show_14_02_2014_part2.mp3', 'morning_show_14_02_2014_part1.mp3', 'morning_show_13_02_2014_part2.mp3', 'morning_show_13_02_2014_part1.mp3');
usort($shows, 'value_compare');
var_dump($shows);
?>
Is it possible to do something like this in PHP?
$index1 = "[0][1][2]";
$index2 = "['cat']['cow']['dog']";
// I want this to be $myArray[0][1][2]
$myArray{$index1} = 'stuff';
// I want this to be $myArray['cat']['cow']['dog']
$myArray{$index2} = 'morestuff';
I've searched for a solution, but I don't think I know the keywords involved in figuring this out.
eval('$myArray[0][1][2] = "stuff";');
eval('$myArray'.$index1.' = "stuff";');
But be careful when using eval and user input as it is vulnerable to code injection attacks.
Not directly. $myArray[$index] would evaluate to $myArray['[0][1][2]']. You would probably have to separate each dimension or write a little function to interpret the string:
function strIndexArray($arr, $indices, $offset = 0) {
$lb = strpos($indices, '[', $offset);
if ($lb === -1) {
return $arr[$indices];
}
else {
$rb = strpos($indices,']', $lb);
$index = substr($indices, $lb, $rb - $lb);
return strIndexArray($arr[$index], substr($indices, $rb+1));
}
}
You can probably find some regular expression to more easily extract the indices which would lead to something like:
$indices = /*regex*/;
$value = '';
foreach($indices as $index) {
$value = $array[$index];
}
To set a value in the array the following function could be used:
function setValue(&$arr, $indices, $value) {
$lb = strpos($indices, '[');
if ($lb === -1) {
$arr = $value;
}
else {
$rb = strpos($indices, ']', $lb);
$index = substr($indices, $lb, $rb);
setValue($arr[$index], substr($indices, $lb, $rb+1), $value);
}
}
Note: I made above code in the answer editor so it may contain a typo or two ; )
$index1 = "[0][1][2]";
$index2 = "['cat']['cow']['dog']";
function myArrayFunc(&$myArray,$myIndex,$myData) {
$myIndex = explode('][',trim($myIndex,'[]'));
$m = &$myArray;
foreach($myIndex as $myNode) {
$myNode = trim($myNode,"'");
$m[$myNode] = NULL;
$m = &$m[$myNode];
}
$m = $myData;
}
// I want this to be $myArray[0][1][2]
myArrayFunc($myArray,$index1,'stuff');
// I want this to be $myArray['cat']['cow']['dog']
myArrayFunc($myArray,$index2,'morestuff');
var_dump($myArray);
There's always the evil eval:
eval('$myArray' . $index1 . ' = "stuff";');
You can use two anonymous functions for this.
$getThatValue = function($array){ return $array[0][1][2]; };
$setThatValue = function(&$array, $val){ $array[0][1][2] = $val; };
$setThatValue($myArray, 'whatever');
$myValue = $getThatValue($myArray);