简体   繁体   中英

How do i str_split text character according to multiple record in query

I have example 2,1,3,2 record for the query $qty in my solution i want to split each 4 diffrent characters from the text line of 1234567810111213141516171819202122232425262728 just according to each record in $qty in achievement my expected output should look like 1234,5678,9101,1121,3141,5161,7181,9202 i have tried:

<?php
require("init.php");
?>
<?php
$sql = mysqli_query($conn, "select * from books where book='1644445'");
while($row = mysqli_fetch_assoc($sql))
{
$qty  = $row["quantity"];  
echo "<br/>$qty"; #result 2132
$plit = "1234567810111213141516171819202122232425262728";
$show_plit = str_split($plit, 4);
for($b = 0; $b<$qty; $b++)
{
echo "<br/>$show_plit[$b]";
}
}
?>

but i get 1234,5678,1234,1234,5678,9101,1234,5678 in output what are mine doing wrong. Big thanks in advances

Because you generate the array from the str_split in every and iterateit each time starting form 0, you only take the first elements. By taking it out of the while loop and saving the old count of b outside the loop as well, your code will not start from the beginning again.

But be warned, you will run into an OutOfBoundsException , if your book qunatity sum is higher than the available number of blocks from your initial string.

Also your string is missing a 9: 12345678 9 10111213141516171819202122232425262728

<?php
$sql = mysqli_query($conn, "select * from books where book='1644445'");
$split = "12345678910111213141516171819202122232425262728";
$show_plit = str_split($split, 4);
$b = 0;
while($row = mysqli_fetch_assoc($sql))
{
    $qty  = $row["quantity"];  
    $oldB = $b;
    echo "<br/>{$qty}"; #result 2132
    for(; $b< $oldB + $qty; $b++)
    {
        echo "<br/>{$show_plit[$b]}";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM