PHP sort array by same value twice - php

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

Related

PHP look-and-say sequence

I'm trying to code Conway look-and-say sequence in PHP.
Here is my code:
function look_and_say ($number) {
$arr = str_split($number . " ");
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
return $res;
}
As I run the function, look_and_say(9900) I am getting value I expected: 2920.
My question is for assigning $arr to be $arr = str_split($number) rather than $arr = str_split($number . " "), the result omits the very last element of the $arr and return 29.
Is it normal to add empty space at the end of the $arr foreach to examine the last element or is there any better way to practice this code - besides regex way.
There are 2 methods I was able to come up with.
1 is to add concatenate at the result after the loop too.
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
$res .= $count . $target;
return $res;
}
And the 2nd one is to add another if clause inside the loop and determine the last iteration:
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
$i=0;
$total = count($arr);
foreach($arr as $num){
if($i == ($total-1))
{
$count++;
$res .= $count . $target;
}
elseif($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
$i++;
}
return $res;
}
I want to suggest you other way using two nested while loops:
<?php
function lookAndSay($number) {
$digits = str_split($number);
$result = '';
$i = 0;
while ($i < count($digits)) {
$lastDigit = $digits[$i];
$count = 0;
while ($i < count($digits) && $lastDigit === $digits[$i]) {
$i++;
$count++;
}
$result .= $count . $lastDigit;
}
return $result;
}

Comma separated string to parent child relationship array php

I have a comma separated string like
$str = "word1,word2,word3";
And i want to make a parent child relationship array from it.
Here is an example:
Try this simply making own function as
$str = "word1,word2,word3";
$res = [];
function makeNested($arr) {
if(count($arr)<2)
return $arr;
$key = array_shift($arr);
return array($key => makeNested($arr));
}
print_r(makeNested(explode(',', $str)));
Demo
function tooLazyToCode($string)
{
$structure = null;
foreach (array_reverse(explode(',', $string)) as $part) {
$structure = ($structure == null) ? $part : array($part => $structure);
}
return $structure;
}
Please check below code it will take half of the time of the above answers:
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
$result = array($arr[$i] => $result);
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
Here is another code for you, it will give you result as you have asked :
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
if($i == 0){
$result = array($arr[$i] => $result);
}else{
$result = array(array($arr[$i] => $result));
}
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';

PHP recursive function nesting level reached

Good day. I have a parcer function that taker an array of string like this:
['str','str2','str2','*str','*str2','**str2','str','str2','str2']
And recursivelly elevates a level those starting with asterix to get this
['str','str2','str2',['str','str2',['str2']],'str','str2','str2']
And the function is:
function recursive_array_parser($ARRAY) {
do {
$i = 0;
$s = null;
$e = null;
$err = false;
foreach ($ARRAY as $item) {
if (!is_array($item)) { //if element is not array
$item = trim($item);
if ($item[0] === '*' && $s == null && $e == null) { //we get it's start and end if it has asterix
$s = $i;
$e = $i;
} elseif ($item[0] === '*' && $e != null)
$e = $i;
elseif (!isset($ARRAY[$i + 1]) || $s != null && $e != null) { //if there are no elements or asterix element ended we elevate it
$e = $e == NULL ? $i : $e;
$head = array_slice($ARRAY, 0, $s);
$_x = [];
$inner = array_slice($ARRAY, $s, $e - $s + 1);
foreach ($inner as $_i)
$_x[] = substr($_i, 1);
$inner = [$_x];
$tail = array_slice($ARRAY, $e + 1, 999) or [];
$X = array_merge($head, $inner);
$ARRAY = array_merge($X, $tail);
$s = null;
$e = null;
$err = true;
}
} else {
$ARRAY[$i] = recursive_array_parser($ARRAY[$i]); //if the item is array of items we recur.
}
$i++;
if ($err == true) {
break 1;
}
}
} while ($err);
return $ARRAY;
}
When this function runs, i get "Fatal error: Maximum function nesting level of '200' reached, aborting!" error.
I know it has something to do with infinite recursion, but i can't track the particular place where it occurs, and this is strange.
I don't normally rewrite code, but your code can be reduced and simplified while, from what I can see, getting the desired result. See if this works for you:
$a = array('a','b','c','*d','*e','**f','g','*h');
print_r($a);
$a = recursive_array_parser($a);
print_r($a);
function recursive_array_parser($array)
{
$ret = array();
for($i=0; $i<sizeof($array); $i++)
{
if($array[$i]{0}!='*') $ret[] = $array[$i];
else
{
$tmp = array();
for($j=$i; $j<sizeof($array) && $array[$j]{0}=='*'; $j++)
{
$tmp[] = substr($array[$j],1);
}
$ret[] = recursive_array_parser($tmp);
$i = $j-1;
}
}
return $ret;
}
Note that it isn't possible for $array[$i] to be an array, so that check is removed. The recursion takes place on the temp array created when a * is found. The $i is closer tied to $array to reset it properly after parsing the series of * elements.
Here's my solution. No nested loops.
function recursive_array_parser($arr) {
$out = array();
$sub = null;
foreach($arr as $item) {
if($item[0] == '*') { // We've hit a special item!
if(!is_array($sub)) { // We're not currently accumulating a sub-array, let's make one!
$sub = array();
}
$sub[] = substr($item, 1); // Add it to the sub-array without the '*'
} else {
if(is_array($sub)) {
// Whoops, we have an active subarray, but this thing didn't start with '*'. End that sub-array
$out[] = recursive_array_parser($sub);
$sub = null;
}
// Take the item
$out[] = $item;
}
}
if(is_array($sub)) { // We ended in an active sub-array. Add it.
$out[] = recursive_array_parser($sub);
$sub = null;
}
return $out;
}

Multiple String Replace Based on Index

I need to replace multiple sections of a string based on their indices.
$string = '01234567890123456789';
$replacements = array(
array(3, 2, 'test'),
array(8, 2, 'haha')
);
$expected_result = '012test567haha0123456789';
Indices in $replacements are expected not to have overlaps.
I have been trying to write my own solution, split the original array into multiple pieces based on sections which needs to be replaced or not, and finally combine them:
echo str_replace_with_indices($string, $replacements);
// outputs the expected result '012test567haha0123456789'
function str_replace_with_indices ($string, $replacements) {
$string_chars = str_split($string);
$string_sections = array();
$replacing = false;
$section = 0;
foreach($string_chars as $char_idx => $char) {
if ($replacing != (($r_idx = replacing($replacements, $char_idx)) !== false)) {
$replacing = !$replacing;
$section++;
}
$string_sections[$section] = $string_sections[$section] ? $string_sections[$section] : array();
$string_sections[$section]['original'] .= $char;
if ($replacing) $string_sections[$section]['new'] = $replacements[$r_idx][2];
}
$string_result = '';
foreach($string_sections as $s) {
$string_result .= ($s['new']) ? $s['new'] : $s['original'];
}
return $string_result;
}
function replacing($replacements, $idx) {
foreach($replacements as $r_idx => $r) {
if ($idx >= $r[0] && $idx < $r[0]+$r[1]) {
return $r_idx;
}
}
return false;
}
Is there any more effective way to achieve the same result?
The above solution doesn't look elegant and feels quite long for string replacement.
Use this
$str = '01234567890123456789';
$rep = array(array(3,3,'test'), array(8,2,'haha'));
$index = 0;
$ctr = 0;
$index_strlen = 0;
foreach($rep as $s)
{
$index = $s[0]+$index_strlen;
$str = substr_replace($str, $s[2], $index, $s[1]);
$index_strlen += strlen($s[2]) - $s[1];
}
echo $str;

Accessing PHP associative array with index represented as string

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

Categories