i have a small problem with the explode function. I have a string like this:
$response:"online,ksksuems,3428939,670605083faeb7750e1afc1010f0f66f8ef0025a,File1.zip
offline,iwksksiw,,, offline,kdlsiwie,,, offline,jdmsmwus,,,
online,uekseks,4023702,37d97c816afdfb10857057d870e74e8774e2bf8a,File2.zip
online,jwksjwa,8860421,20b5e3154653f24963d005cd873917d3cc0a0fe2,File3.rar
online,jsusneus,4912753,9489a47bac4d2a4f7f6810cb37f60924ef48fc48,File4.rar
online,udjdjsis,1177526,5d1da2a1aebae206908ef6d88105f5272ab423e0,File5.zip"
Now I wanted to use the explode function:
list($fileStatus, $fileId, $fileSize, $fileSha1, $fileName) = explode(",", $response);
But I will only get 1 response, if I print the content of $fileStatus. My Question now, how can i get an array for each variable? So that i have "array(ksksuems => online, iwksksiw => offline);" ?
You need to use explode() on your response to put the individual responses into an array and then loop through it to get each other values.
Assuming a the new line character of \n as the separator:
$responses = explode("\n", $response);
foreach ($responses as $resp) {
list($fileStatus, $fileId, $fileSize, $fileSha1, $fileName) = explode(",", $resp);
// do stuff
}
This should work -
$arr = Array();
$lines = explode("\r\n", $response);
//print the exploded lines here.
var_dump($lines);
/*
Expected output -
array
0 => string 'online,ksksuems,3428939,670605083faeb7750e1afc1010f0f66f8ef0025a,File1.zip' (length=74)
1 => string 'offline,iwksksiw,,, offline,kdlsiwie,,, offline,jdmsmwus,,,' (length=59)
2 => string 'online,uekseks,4023702,37d97c816afdfb10857057d870e74e8774e2bf8a,File2.zip' (length=73)
3 => string 'online,jwksjwa,8860421,20b5e3154653f24963d005cd873917d3cc0a0fe2,File3.rar' (length=73)
4 => string 'online,jsusneus,4912753,9489a47bac4d2a4f7f6810cb37f60924ef48fc48,File4.rar' (length=74)
5 => string 'online,udjdjsis,1177526,5d1da2a1aebae206908ef6d88105f5272ab423e0,File5.zip' (length=74)
*/
foreach($lines as $line){
list($fileStatus, $fileId, $fileSize, $fileSha1, $fileName) = explode(",", $line);
$arr[$fileId] = $fileStatus;
}
var_dump($arr);
/*
OUTPUT-
array
'ksksuems' => string 'online' (length=6)
'iwksksiw' => string 'offline' (length=7)
'uekseks' => string 'online' (length=6)
'jwksjwa' => string 'online' (length=6)
'jsusneus' => string 'online' (length=6)
'udjdjsis' => string 'online' (length=6)
*/
Related
I have a String in this format
{value=very big +$5},{value=super big +$10},{value=extra big +$15}
How to convert them into 2 Arrays in such format?
For example:
$name=["very big","super big","extra big"];
$price=["5","10","15"]; // OR $price=[5,10,15];
I can do that by using explode() if the string format is in a simpler format. However, this format is too complicated. Anyone knows how to do that ?
use explode with ',' ,'=' ,'+$'
$string = "{value=very big +$5},{value=super big +$10},{value=extra big +$15}";
$temp_array = (explode(",",$string));
foreach($temp_array as $val)
{
$temp_array = (explode("=",$val));
$temp_string = $temp_array[1];
$temp_string = str_replace("}","",$temp_string);
$temp_array = (explode("+$",$temp_string));
$name[] = $temp_array[0];
$price[] = $temp_array[1];
}
DEMO
You may try it like the Snippet below suggests. Quick-Test: Here.
<?php
$string = '{value=very big +$5},{value=super big +$10},{value=extra big +$15}';
$arrParts = explode(',', $string);
$name = [];
$price = [];
$result = [];
foreach($arrParts as $iKey=>$part){
$block = preg_replace(["#^\{.*?=#", "#\}$#"], "", $part);
$segments = preg_split("#\s#", $block); //<== CREATE AN ARRAY WITH 3 COLUMNS
list($val1, $val2, $val3) = $segments;
$namePart = $val1 . " {$val2}";
$pricePart = preg_replace("#[\+\-\$]#", "",$val3);
$name[] = $namePart;
$price[] = $pricePart;
// BONUS: JUST CREATE A 3RD ARRAY WITH NAMED-KEY
$result[$namePart] = $pricePart;
}
var_dump($name);
//YIELDS::
array (size=3)
0 => string 'very big' (length=8)
1 => string 'super big' (length=9)
2 => string 'extra big' (length=9)
var_dump($price);
//YIELDS::
array (size=3)
0 => string '5' (length=1)
1 => string '10' (length=2)
2 => string '15' (length=2)
var_dump($result);
//YIELDS::
array (size=3)
'very big' => string '5' (length=1)
'super big' => string '10' (length=2)
'extra big' => string '15' (length=2)
You can use regex, for example this should work:
preg_match_all('/value=([\w\s]+)\s\+/', $string, $matches)
preg_match_all('/\$([\d]+)\}/', $string, $matches)
I am making a function that can help me to cast the string to array, but that strange when the function always add first character to the array. Thank at first and this is code i used in function:
$string = '0:009987;1:12312;2:45231;3:00985;3:10923;4:11253;4:62341;4:01102;4:58710;4:10102;4:87093;4:12034;5:9801;6:1092;6:4305;6:1090;7:450;8:34';
$explodedString = explode(';', $string);
//var_dump($explodedString);
$takeArray = array();
$counti = 0;
foreach($explodedString as $exploded){
$secondExp = explode(':', $exploded);
var_dump($secondExp);
if(isset($takeArray[$secondExp[0]])){
$takeArray[$secondExp[0]][$counti] = $secondExp[1];
}else{
$takeArray[$secondExp[0]] = $secondExp[1];
}
$counti++;
}
var_dump($takeArray);
This is current output of this code:
array (size=9)
0 => string '009987' (length=6)
1 => string '12312' (length=5)
2 => string '45231' (length=5)
3 => string '00981' (length=5)
4 => string '11253 605181' (length=12)
5 => string '9801' (length=4)
6 => string '1092 41' (length=16)
7 => string '450' (length=3)
8 => string '34' (length=2)
Looking into row 4 you will see the string: '605181', this string come from the first character of each value belong to 4. But i need an output array like this:
[0] => {'009987'},
....
[4] => { '11253', '62341', ...., },
....
Please help me.
I'm not sure why you need $counti. All you need to do is, initialize the $takeArray[$n] if it doesn't exists, and push a new value to it. Something like this:
if(!isset($takeArray[$secondExp[0]])) {
// Initialize the array
$takeArray[$secondExp[0]] = array();
}
// Push the new value to the array
$takeArray[$secondExp[0]][] = $secondExp[1];
You only need to do the following :
$takeArray = array();
foreach($explodedString as $exploded) {
$secondExp = explode(':', $exploded);
$takeArray[(int)$secondExp[0]][] = $secondExp[1];
}
$string = '0:009987;1:12312;2:45231;3:00985;3:10923;4:11253;4:62341;4:01102;4:58710;4:10102;4:87093;4:12034;5:9801;6:1092;6:4305;6:1090;7:450;8:34';
$explodedString = explode(';', $string);
$takeArray = array();
foreach($explodedString as $exploded)
{
$secondExp = explode(':', $exploded);
$takeArray[$secondExp[0]][] = $secondExp[1];
}
var_dump($takeArray);
I have strings like the following that I have to split:
Other,CODSITE,Items::getCodCdeCli+Address::getNameAddress
Other,CODSITE,Items::getCodCdeCli
Items::getCode+Address::getName,CODSITE+Items::getSample,Items::getItemID
Other, CODSITE, CODSITE2
Into:
array(
array(
0 => 'Other',
1 => 'CODSITE',
2 => array(
'Items' => 'getCodCdeCli',
'Address' => 'getNameAddress'
)
),
//...
)
Each comma involve new information, if we have a '+' we need to append both data. If we have '::' we need to get first part as key of the result information.
For beginning this solution I have tried to split this on comma:
$re = "/([^,]+)/";
$str = "Other,CODSITE,Items::getCodCdeCli+Address::getNameAddress";
preg_match_all($re, $str, $matches);
for now with this regex I have this:
array (size=2)
0 =>
array (size=3)
0 => string 'Other' (length=5)
1 => string 'CODSITE' (length=7)
2 => string 'Items::getCodCdeCli+Address::getNameAddress' (length=43)
1 =>
array (size=3)
0 => string 'Other' (length=5)
1 => string 'CODSITE' (length=7)
2 => string 'Items::getCodCdeCli+Address::getNameAddress' (length=43)
Which is wrong. I have same result twice.. and line 2 => [...] is not split (which is normal with my regex)
One way of doing it in single pass is by using array_combine function like this:
$str = 'Other,CODSITE,Items::getCodCdeCli+Address::getNameAddress';
if ( preg_match_all('~(?|[,+]([^,+]+)::([^,+]+)|([^,]+))~', $str, $m) )
print_r( array_combine ( $m[1], $m[2] ) );
Output:
Array
(
[Other] =>
[CODSITE] =>
[Items] => getCodCdeCli
[Address] => getNameAddress
)
Does it need to be regex? It might be possible to achieve this with a couple of explodes and foreach loops:
$str = 'Other,CODSITE,Items::getCodCdeCli+Address::getNameAddress';
//new entry per comma (,)
$results = explode(',',$str);
//check each entry for array information
foreach($results as &$result) {
if(strpos($result,'+') !== FALSE) {
//explode array information
$bits1 = explode('+',$result);
$result = array();
foreach($bits1 as &$subresult) {
//format array information into key => value pairs
if(strpos($subresult,'::') !== FALSE) {
$bits = explode('::',$subresult);
$result[$bits[0]] = $bits[1];
}
}
}
}
var_dump($results);
/**
* array (size=3)
* 0 => string 'Other' (length=5)
* 1 => string 'CODSITE' (length=7)
* 2 => array (size=2)
* 'Items' => string 'getCodCdeCli' (length=12)
* 'Address' => string 'getNameAddress' (length=14)
*/
With the help of #Richard Parnaby-King answer. This is the solution, in fact no regex is needed even if i'm sure we can use it for the same result.
$lines = array(
0 => 'Other,CODSITE,Items::getCodCdeCli+Address::getNameAddress',
2 => 'Other,CODSITE,Items::getCodCdeCli',
3 => 'Items::getCode+Address::getName,CODSITE+Items::getSample,Items::getItemID',
4 => 'Other, CODSITE, CODSITE2',
);
foreach ($lines as $input) {
$informations = explode(',', $input);
$result = array();
foreach ($informations as $information) {
if(strpos($information, '+') !== FALSE) {
$classes = explode('+',$information);
$temp = array();
foreach($classes as $subresult) {
if(strpos($subresult,'::') !== FALSE) {
$classAndMethod = explode('::',$subresult);
$temp[$classAndMethod[0]] = $classAndMethod[1];
} else {
$temp[] = trim($subresult);
}
}
$result[] = $temp;
} elseif (strpos($information, '::') !== FALSE) {
$classAndMethod = explode('::',$information);
$result[][$classAndMethod[0]] = $classAndMethod[1];
} else {
$result[] = trim($information);
}
}
var_dump($result);
}
It works !
In my project, i will have to receive a string from user (in textarea). Now this string will be converted into array. Now the problem is that, the character length must be minimum of 3,
in the following array next element should be joined to current one if character length is less than 3. How to perform it in PHP.
a[0]=>this a[1]=>is a[2]=>an a[3]=>example a[4]=>array.
Output should be:
a[0]=>this a[1]=>isan a[2]=>example a[3]=>array.
Just try with:
$input = ['this', 'is', 'an', 'example', 'array.'];
$output = [];
$part = '';
foreach ($input as $value) {
$part .= $value;
if (strlen($part) > 3) {
$output[] = $part;
$part = '';
}
}
Output:
array (size=4)
0 => string 'this' (length=4)
1 => string 'isan' (length=4)
2 => string 'example' (length=7)
3 => string 'array.' (length=6)
I'm using urlencode & urldecode to pass variables trough a html-form.
$info = 'tempId='.$rows['tempID'].'&tempType='.$rows['tempType'].'&dbId='.$rows['ID'];
echo '<input type="hidden" name="rank[]" value="'.urlencode($info).'" >';
Here is what is in $rows
array (size=4)
'ID' => string '110' (length=3)
'tempID' => string '1' (length=1)
'tempType' => string 'temp_first' (length=10)
'pageOrder' => string '0' (length=1)
So $info is
tempId=1&tempType=temp_first&dbId=110
But if i then decode it, it losses 1 parameter. How is this possible?
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk);
$tempId = urldecode($param[0]); // template id
$tempType = urldecode($param[1]); // Template type
$dbId = urldecode($param[2]); // database ID
var_dump($param);
}
Output:
array (size=2)
0 => string 'dbId' (length=4)
1 => string '110' (length=3)
Sometime there are even things in the array wich should not be in there, for example instead of temp_first it says tempType. Just the variable name.
I hope you guys can help me
There's no need to explode and process the string manually, you can use parse_str():
parse_str(urldecode($list[$i]), $output);
var_dump($output);
Would output:
array
'tempId' => string '1' (length=1)
'tempType' => string 'temp_first' (length=10)
'dbId' => string '110' (length=3)
try this
$result=array();
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk);
$result[$param[0]]=$param[1];
}
var_dump($result);
Could you try this and check the result (I'm groping in the dark though):
//change this <input type="hidden" name="rank[]" value="'.urlencode($info).'" > to
//<input type="hidden" name="urlargs" value="'.urlencode($info).'" >
$values = explode('&',urldecode($_POST['urlargs']));
$arguments = array();
foreach($values as $argument_set){
$data = explode('=',$argument_set);
$arguments[$data[0]] = $data[1];
}
var_dump($arguments);
I believe the problem is in the way you're processing the value
$data=array();
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk); //
$data[$param[0]]=$param[1]
}
Instead of grouping all code together, start by putting it in seperate vars and echo the content for debugging. Because you are saying you loose one variable, but the output you show is just one of the variables. What is the var_dump of the other two?
Because your var_dump($param); would output the part before the '=' and after the '=', so indeed i would expect the output to be something like: So which one of these are you missing?
array (size=2)
0 => string 'tempId' (length=6)
1 => string '1' (length=1)
array (size=2)
0 => string 'tempType' (length=8)
1 => string 'temp_first' (length=10)
array (size=2)
0 => string 'dbId' (length=4)
1 => string '110' (length=3)
DEBUG code:
foreach ($list as $row) {
echo 'Full row:: '. $row.'<br>';
//if the data is comming via GET or POST, its already decoded and no need to do it again
$split = explode('&', urldecode($row));
foreach($split as $chunk) {
echo 'Chunk:: '.$chunk.'<br>';
$param = explode('=', $chunk);
echo 'param name:: '.$param[0].'<br>';
echo 'param value:: '.$param[1].'<br>';
}
}