logo
down
shadow

Implode sorted number array to string by commas and merge intervals


Implode sorted number array to string by commas and merge intervals

By : Younes Jarmouni
Date : November 21 2020, 09:01 AM
hope this fix your issue This should work for you:
First for every iteration we simply append the current number of the iteration to the $result string:
code :
$result .= $arr[$i];
//(1)Check if next element exists     (2)Check if next element follows up the prev one
      ┌───────┴───────┐    ┌───────────┴────────────┐      
while(isset($arr[$i+1]) && $arr[$i] + 1 == $arr[$i+1] && ++$range)
    $i++;
if($range)
    $result .= "-" . $arr[$i];
if($i+1 < $l)
    $result .= ",";
<?php

    $arr = array(1,2,3,6,8,9);
    $result = "";
    $range = 0;

    for($i = 0, $l = count($arr); $i < $l; $i++){

        $result .= $arr[$i];

        while(isset($arr[$i+1]) && $arr[$i] + 1 == $arr[$i+1] && ++$range)
            $i++;

        if($range)
            $result .= "-" . $arr[$i];

        if($i+1 < $l)
            $result .= ",";

        $range = 0;   

    }

    echo $result;

?>
1-3,6,8-9


Share : facebook icon twitter icon
Remove all commas caused by array before or after implode

Remove all commas caused by array before or after implode


By : wdfeww
Date : March 29 2020, 07:55 AM
it should still fix some issue The implode function is what adds the commas in the first place. So don't use a comma as the "glue" argument of the implode function.
You can use
code :
implode(' ',$cars);
implode('',$cars);
Merge two sorted lists of intervals

Merge two sorted lists of intervals


By : M Duffin
Date : March 29 2020, 07:55 AM
wish helps you Here is a different approach, in the spirit of the answer to the question of overlaps.
code :
<!--code lang=scala--> 
def findUnite (l1: List[Interval], l2: List[Interval]): List[Interval] = (l1, l2) match {
    case (Nil, Nil) => Nil
    case (as, Nil)  => as
    case (Nil, bs)  => bs
    case (a :: as, b :: bs) => {
             if (a.lower > b.upper) b :: findUnite (l1, bs)
        else if (a.upper < b.lower) a :: findUnite (as, l2)
        else if (a.upper > b.upper) findUnite (a.union (b).get :: as, bs)
        else                        findUnite (as, a.union (b).get :: bs)
    }
}
<!--code scala--> 
case class Interval (lower: Int, upper: Int) {
    // from former question, to compare
    def overlap (other: Interval) : Option [Interval] = {
        if (lower > other.upper || upper < other.lower) None else
        Some (Interval (Math.max (lower, other.lower), Math.min (upper, other.upper)))
    }

    def union (other: Interval) : Option [Interval] = {
        if (lower > other.upper || upper < other.lower) None else
        Some (Interval (Math.min (lower, other.lower), Math.max (upper, other.upper)))
    }    
}
lower   upper
_____________
    2    4 
    3    5 
_____________
min 2    4 
max 3    5 
<!--code lang='scala'--> 
val e = List (Interval (0, 4), Interval (7, 12))
val f = List (Interval (1, 3), Interval (6, 8), Interval (9, 11))
findUnite (e, f)
// res3: List[Interval] = List(Interval(0,4), Interval(6,12))
val e = List (Interval (0, 4), Interval (7, 12))
val f = List (Interval (1, 3), Interval (5, 8), Interval (9, 11))
findUnite (e, f)
// res6: List[Interval] = List(Interval(0,4), Interval(5,12))
Merge an array with a string variable in PHP implode

Merge an array with a string variable in PHP implode


By : Karel Hagel
Date : March 29 2020, 07:55 AM
help you fix your problem If $a is an array and $q is the prefix string you can achieve that with 2 steps:
Add the prefix with:
code :
$a = array("com", "co");
$q = "robot.";
foreach ($a as &$value)
    $value = $q.$value;
echo implode(',',$a);
robot.com,robot.co
$a = array("com", "co", "org");
$q = "robot.c";
$arr =  explode(".", $q);

$output = array();
foreach ($a as &$value) {
    if (substr($value, 0, strlen($arr[1])) === $arr[1])
        $output[]= $arr[0] . "." . $value;
}
echo implode(',',$output);
how to remove the last two commas in an array after using the implode function

how to remove the last two commas in an array after using the implode function


By : Largou
Date : March 29 2020, 07:55 AM
this one helps. There are two possibilities as far as I can see.
trim() only removes spaces, so to trim commas as well you need to add what characters it should trim (commas and spaces in this example)...
code :
$doctors = trim($doctors, ", ");
$doctors = array_filter($_POST['doctors']);
Array implode to MySql and then retrieve values and explode back to same array not working if commas already existed in

Array implode to MySql and then retrieve values and explode back to same array not working if commas already existed in


By : user3719267
Date : March 29 2020, 07:55 AM
wish helps you If I implode an array $arr = ["Hello my, name is Steve", "How are you?"] to string to insert to MySQL database like so: $data = implode(',',$arr);, when I try to retrieve those values and explode it back into array: $arr2 = explode(',',$data); it returns : ["Hello my", "name is Steve", "How are you?"] , Instead you can use json_encode and json_decode.
Try this out:
code :
$arr = ["Hello my, name is Steve", "How are you?"]
$data = json_encode($arr); //Insert $data into mysql 
//Then to retrieve values 
$arr2 = json_decode($data); //returns ["Hello my, name is Steve", "How are you?"]
Related Posts Related Posts :
  • Request error when processing form in controller
  • Can't save xml file content in mysql with fopen/fwrite/fclose (php)
  • Read only Title from a page?
  • PHP - make echo permanent and visible to all viewers
  • composer fails on server with redmine installed
  • Using foreach With Variables on Smarty
  • How do you specify single print blocks when looping through a 'for' loop?
  • PHP: $_FILES returns empty
  • Symfony2 associative array in entity
  • How do I log every output from a PHP script from the command line?
  • How to implement this json feed into a database structure?
  • Codeigniter, windows, xampp, how to use htaccess to get rid of trailing slash?
  • How to disable Navbar and footer in Yii2 other layouts
  • Json not encode my Special Character
  • echo if POST length is low
  • Warning: require_once error
  • What is this code meaning...?
  • Send to /dev/null a PHP function "echo" output
  • How to store post details and timestamp in database?
  • php mysql - search a row and concatenate values of every columns to variable string
  • Write a program to get N number of positive non-zero integers, so that the sum and product of these numbers are equal
  • Running two multi line queries in PHP
  • PHP/ASP Trouble understanding
  • Strict standards notices View/Layout class
  • how to have backwards reference on PHP's regex?
  • Uncaught exception 'RuntimeException' with message 'Unable to load ZF2. Run `php composer.phar install` or define a ZF2_
  • phpDocumentor: DocBlock with @var tags duplicates descriptions
  • how to push an object to an array within an object with PHP
  • Undefined offset error in for loop
  • mysql query logic for fetching data from 3 related tables on certain condition
  • Saving blob video with php
  • SpeckPaypal ZF2 How to edit the CURRENCY CODE?
  • How to filter associated HABTM data with FriendsOfCake Search for CakePHP 3
  • Check ALL $_POST lengths
  • PHP - Recursively set each array element's key to the value of a child element when given the childs key name
  • How to disable the user from entering wrong passwords
  • SilverStripe Custom Email Form - jQuery.ajax not passing variables to server
  • Regular expression to extract Facebook URL's inc vanity
  • Show Calculated Field on SuiteCRM Dashlet
  • Class 'NumberFormatter' not found error in simple PHP program
  • Is it necessary to set values to a variable two times?
  • Scan Barcode - Save Code in SQL Database
  • Fetch MySQLi with custom database (aka, column names for array keys)
  • Symfony2 PagerFantaBundle
  • Wordpress: Restrict file uploads by MIME type
  • Find key in array in a foreach
  • pdo select query wont works with string of letters
  • Check if atleast one character is in mysql row, using php
  • Php method not being called
  • Display dates in a HTML table for each month with PHP
  • VBA Submit Button Clicking
  • Can a namespace start with a number in PHP?
  • Regex not matching regex in PHP
  • Injecting Artisan into Service class
  • Create and transfert array php
  • How do I query MongoDB from PHP with IFNULL() expression inside WHERE?
  • How to download a view block as PDF in drupal 7?
  • PHP - Where should mysql_close() be put in if-else clause?
  • "php comment" within an echo statement
  • Replacing string by boolean in a JSON string?
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co