I am having the following problem. I have the numbers 1/2/3/4/5/6 and I want to separate them into two groups 1/3/5 and 2/4/6. The selection must take place based on the position. This part works ok. The problem comes when I want to group them again, when I use the implode function; it only sees the last number that was stored. I know it has something to do with me using this notation (I chose this way since the amount of numbers to classify varies every time):
$q++;
$row0 = $row0 + 2;
$row1 = $row1 + 2;
but I can't figure a way to fix it or another way to get the same result. Hopefully someone here can point me in the right direction. I left the complete code below.
<?
$string = "1/2/3/4/5/6";
$splitted = explode("/",$string);
$cnt = count($splitted);
$q=0;
$row0=0;
$row1=1;
while($cnt > 2*$q)
{
$p_row = implode(array($splitted[$row0]));
echo "$p_row <br>";
$i_row = implode(array($splitted[$row1]));
echo "$i_row <br>";
$q++;
$row0 = $row0 + 2;
$row1 = $row1 + 2;
}
$out = "implode(',', $i_row)";
var_dump($out);
?>
I missread the problem it seems. Instead I give this optimization.
$string = "1/2/3/4/5/6";
$splitted = explode("/", $string);
$group = array();
for ($index = 0, $t = count($splitted); $index < $t; ++$index) {
$group[$index & 1][] = $splitted[$index];
}
$oddIndex = $group[0]; //start with index 1
$evenIndex = $group[1]; //start with index 2
echo "odd index: "
. implode('/', $oddIndex)
. "\neven index: "
. implode('/', $evenIndex)
. "\n";
You can split the array into groups using % on loop index. Put each group in separate array. Here is example:
<?php
$string = "1/2/3/4/5/6";
$splitted = explode("/",$string);
$group_odd = array(); ## all odd elements of $splitted come here
$group_even = array(); ## all even elements of $splitted come here
for ($index = 0; $index < count($splitted); ++$index) {
## if number is divided by 2 with rest then it's odd
## but we've started calculation from 0, so we need to add 1
if (($index+1) % 2) {
$group_odd[] = $splitted[$index];
}
else {
$group_even[] = $splitted[$index];
}
}
echo implode('/', $group_odd), "<br />"; ## outputs "1/3/5<br />"
echo implode('/', $group_even), "<br />"; ## outputs "2/4/6<br />"
print_r($group_odd);
print_r($group_even);
?>
Based on their position? So, split based on the evenness/oddness of their index in the array?
Something like this?
<?php
$string = "1/2/3/4/5/6";
list( $evenKeys, $oddKeys ) = array_split_custom( explode( '/', $string ) );
echo '<pre>';
print_r( $evenKeys );
print_r( $oddKeys );
function array_split_custom( array $input )
{
$evens = array();
$odds = array();
foreach ( $input as $index => $value )
{
if ( $index & 1 )
{
$odds[] = $value;
} else {
$evens[] = $value;
}
}
return array( $evens, $odds );
}
Related
I want to build a combination of numbers and letters separated by - (minus sign). i.e 1-R-3. The first number are in an array called $Points ,the letters are stored in a array called $Color and the last number is in a third array called $Points2;
$Points = [1,2,3,4];
$Color = [R,B,V,Y];
$Points = [1,2,3,4];
I want the result to be one one row 1-R-1, 2-B-2 and so on. Now the result outputs as:
1
(minus sign)
R
(minus sign)
3
`
$Bind = "-";
$foo = $Points[0] . $Bind . $Points[1];
I have tried to convert the integer to a string by (String) but have not worked.
Can somebody help me to get the result on one line? I bet i'm missing something easy!
EDIT: The format in the arrays where incorrect since I forgot ->plaintext when doing my web-scraping.
/U
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
foreach ($Points as $point=>$value) {
echo $value . '-' . $Color[$point] . '-' . $value . PHP_EOL;
}
Note that the values in the $Color array need to be in quotes to avoid errors.
You have two arrays called $Points, so I've renamed one.
This just combines the three arrays by using foreach and using the key of each element and using it to access the other arrays at the same index...
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
$Points1 = [1,2,3,4];
$bind = "-";
foreach ( $Points as $key => $val ) {
echo $val.$bind.$Color[$key].$bind.$Points1[$key].PHP_EOL;
}
This may be occurring because of the tabs or carriage return:
<?php
$points = [1,2,3,4];
$colors = ['R','B','V','Y'];
$bind = '-';
$foo = [];
for ($x = 0; $x <= 3; $x++) {
$foo[$x] = $points[$x].$bind.$colors[$x].$bind.$points[$x];
}
foreach($foo as $value) {
echo $value.'<br>';
}
?>
Result:
1-R-1
2-B-2
3-V-3
4-Y-4
You can use php join function. For example:
$results = [];
for ($i = 0; $i < count($Points); $i++) {
$results[] = join('-', [$Points[$i], $Colors[$i], $Points2[$i]]);
}
// Now you have your combined values in $results array
var_export($results);
You can combine array into one string like
<?php
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
$Points = [1,2,3,4];
$result='';
$bind='-';
foreach ($Points as $index => $value) {
$result .= $value .$bind . $Color[$index] . $bind . $value.PHP_EOL;
}
echo $result;
?>
DEMO
i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}
Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}
You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66
This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>
I want to parse and expand the given strings in PHP.
From
0605052&&-5&-7&-8
0605052&&-4&-7
0605050&&-2&-4&-6&-8
To
0605052, 0605053 ,0605054 ,0605055, 0605057, 0605058
0605052,0605053,0605054,0605057
0605050,0605051,0605052,0605054,0605056,0605058
can someone help me with that? thanks in advance!
Your question is not very clear, but I think you mean a solution like this:
Edited: Now the hole ranges were shown and not only the specified numbers.
<?php
$string = "0605052&&-5&-7&-8";
$test = '/^([0-9]+)\&+/';
preg_match($test, $string, $res);
if (isset($res[1]))
{
$nr = $res[1];
$test = '/\&\-([0-9])/';
preg_match_all($test, $string, $res);
$result[] = $nr;
$nrPart = substr($nr, 0, -1);
$firstPart = substr($nr, -1);
if (isset($res[1]))
{
foreach ($res[1] as &$value)
{
if ($firstPart !== false)
{
for ($i=$firstPart+1; $i<=$value; $i++)
{
$nr = $nrPart . $i;
$result[] = $nr;
}
$firstPart = false;
}
else
{
$nr = $nrPart . $value;
$result[] = $nr;
$firstPart = $value;
}
}
}
var_dump($result);
}
?>
This delivers:
result[0] = "0605052"
result[1] = "0605053"
result[2] = "0605054"
result[3] = "0605055"
result[4] = "0605057"
result[5] = "0605058"
I think a multi step approach is the best thing to do here.
E.g. take this as an example 0605052&&-5&-7&-8:
Split at -. The result will be 0605052&&, 5&, 7&, 8
The first result 0605052&& will help you create your base. Simply substring the numbers by finding first occurence of & and substring to the next to last number. Result will be 060505. You will also need the last number, so get it as well (which is 2 in this case).
Get the remaining ends now, all \d& are simple to get, simply take the first character of the string (or if those can be more than one number, use substring with first occurence of & approach again).
The last number is simple: it is 8.
Now you got all important values. You can generate your result:
The last number from 2., all numbers from 3. and the number from 4. together with your base are the first part. In addition, you need to generate all numbers from the last number of 2. and the first result of 3. in a loop by a step of 1 and append it to your base.
Example Code:
<?php
$str = '0605052&&-5&-7&-8';
$split = explode('-', $str);
$firstAmpBase = strpos($split[0], '&');
$base = substr($split[0], 0, $firstAmpBase - 1);
$firstEnd = substr($split[0], $firstAmpBase - 1, 1);
$ends = [];
$firstSingleNumber = substr($split[1], 0, strpos($split[1], '&'));
for ($i = $firstEnd; $i < $firstSingleNumber; $i++) {
array_push($ends, $i);
}
array_push($ends, $firstSingleNumber);
for ($i = 2; $i < count($split) - 1; $i++) {
array_push($ends, substr($split[$i], 0, strpos($split[$i], '&')));
}
array_push($ends, $split[count($split) - 1]);
foreach ($ends as $end) {
echo $base . $end . '<br>';
}
?>
Output:
0605052
0605053
0605054
0605055
0605057
0605058
Lets say i have url like this
$a= "http://zz.com/1/2/3/4/5/6/7";
say that url can have many step like 1 ,2 ,3 say something it have up to 3 or sometime up to 7
I want to get url like this from $a
$b="http://zz.com/";
$c="http://zz.com/1/";
$d="http://zz.com/1/2/";
$e="http://zz.com/1/2/3/";
...
...
$k= "http://zz.com/1/2/3/4/5/6/;
Is it possible to do such things in php?
Thank you very much .
I tried to use php url parse and explode but get empty value in beginning and end of array.
Very simple way is to use explode() function.
[EDIT] made it use letters as variables if that was necessary
$a= "http://zz.com/14/2/13/4/5/8/7";
//grab the protocol and addy
$x = explode('//',$a);
$y = explode('/',$x[1]);
$letters = array();
$letters[1] = 'a';
$letters[2] = 'b';
$letters[3] = 'c';
$letters[4] = 'd';
$letters[5] = 'e';
$letters[6] = 'f';
$letters[7] = 'g';
$letters[8] = 'h';
$letters[9] = 'i';
$letters[10] = 'j';
//loop through various steps
for($i = 1; $i<=count($y); $i++)
{
$$letters[$i] = $x[0].'//'.$y[0].'/';
for($k=0; $k<$i; $k++)
{
$$letters[$i] .= $y[$k].'/';
}
}
echo $a."\n";
echo $b."\n";
echo $c."\n";
echo $d."\n";
echo $e."\n";
echo $f."\n";
echo $g."\n";
echo $h."\n";
that will output:
http://zz.com/zz.com/
http://zz.com/zz.com/14/
http://zz.com/zz.com/14/2/
http://zz.com/zz.com/14/2/13/
http://zz.com/zz.com/14/2/13/4/
http://zz.com/zz.com/14/2/13/4/5/
http://zz.com/zz.com/14/2/13/4/5/8/
http://zz.com/zz.com/14/2/13/4/5/8/7/
You can see the code working here: http://sandbox.onlinephpfunctions.com/code/4c0446acaf0fd298fc089b743da5a807529e3e0b
[EDIT: with letters here]http://sandbox.onlinephpfunctions.com/code/bb655992fa81f0005938d86697e91272dc57425a
you can try this code:-
<?php
$a= $_SERVER['REQUEST_URI'];//"http://zz.com/1/2/3";
$url = explode('/',str_replace('http://', '', $a));
$next_num = count($url);
echo $next_url = $a.'/'.$next_num;//wil print :- http://zz.com/1/2/3/4
?>
Yes you can and it is pretty easy and it is good to use build in function called parse_url() which extracts some parts of URL.
$url = "http://zz.com/1/2/3/4/5/6/7";
$pathvars = parse_url($url);
$urls = [];
$glue = '';
$counter = 'a';
foreach ($path as $part) {
$glue .= "$part/";
$urls[$counter++] = sprintf("%s://%s%s", $pathvars['scheme'], substr($pathvars['host'], 0, strlen($pathvars['host']) -1), substr($glue, 0, strlen($glue) - 1));
}
// extract to variables
extract($urls, EXTR_OVERWRITE);
echo $a . PHP_EOL;
echo $b . PHP_EOL;
echo $c . PHP_EOL;
echo $d . PHP_EOL; // etc
print_r($urls); // all array of urls
I want to merge 2 element in array in PHP how can i do that. Please any on tell me.
$arr = array('Hello','World!','Beautiful','Day!'); // these is my input
//i want output like
array('Hello World!','Beautiful Day!');
The generic solution would be something like this:
$result = array_map(function($pair) {
return join(' ', $pair);
}, array_chunk($arr, 2));
It joins together words in pairs, so 1st and 2nd, 3rd and 4th, etc.
Specific to that case, it'd be very simple:
$result = array($arr[0].' '.$arr[1], $arr[2].' '.$arr[3]);
A more general approach would be
$result = array();
for ($i = 0; $i < count($arr); $i += 2) {
if (isset($arr[$i+1])) {
$result[] = $arr[$i] . ' ' . $arr[$i+1];
}
else {
$result[] = $arr[$i];
}
}
In case your array is not fixed to 4 elements
$arr = array();
$i = 0;
foreach($array as $v){
if (($i++) % 2==0)
$arr[]=$v.' ';
else {
$arr[count($arr)-1].=$v;
}
}
Live: http://ideone.com/VUixMS
Presuming you dont know the total number of elements, but do know they will always an even number (else you cant join the last element), you can simply iterate $arr in steps of 2:
$count = count($arr);
$out=[];
for($i=0; $i<$count; $i+=2;){
$out[] = $arr[$i] . ' ' .$arr[$i+1];
}
var_dump($out);
Here it is:
$arr = array('Hello', 'World!', 'Beautiful', 'Day!');
$result = array();
foreach ($arr as $key => $value) {
if (($key % 2 == 0) && (isset($arr[$key + 1]))) {
$result[] = $value . " " . $arr[$key + 1];
}
}
print_r($result);
A easy solution would be:
$new_arr=array($arr[0]." ".$arr[1], $arr[2]." ".$arr[3]);