This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How do i Loop through the hidden field items and put in Session using PHP
I have a hidden Field which contains this format which contains the Set of rows separated by ';'(semicolon)
and each row contains some columns name separated by ':' (colon) and each column value separated by ',' (comma)
so my format would be ENO:123,ENAME:XYZ,SAL:1200; ENO:598,ENAME:AIR,SAL:1300; which is what stored in hidden field
So How do i grab each column such as ENO ,ENAME and SAL their values for any number of rows written to hidden field
so i have my own custom session function where i can set the key and value .So on looping the values
I should be able to put MyCustomSessionFunction('ENAME',??????).How do i fill this .
I did not get Proper Replies Earlier .can anyone please help me
$hiddenformat = $_POST['hiddenfield'];
string(80) "ENO:1000,ENAME:B,SAL:10;ENO:1000,ENAME:S,SAL:100;"
when i vardump($hiddenformat) I am getting the above format .How do i explode and loop and assign each value to my
custom session function
foreach( $outer_array as $outer_key => $inner_array )
{
foreach( $inner_array as $key => $value )
{
}
}
$hiddenformat = $_POST['hiddenfield'];
$parts = explode(',', $hiddenformat);
foreach($parts as $part) {
$bits = explode(':', $part);
...
}
Given a $hiddenformat of ENO:1000,ENAME:B,SAL:..., the first explode will split the line at every comma, giving you a $parts array that looks like:
$parts = array(
0 => 'ENO:1000',
1 => 'ENAME:B',
2 => 'SAL:.....
);
Yuu use foreach to loop over this $parts array, and split the $part at every colon (:). So at each stage, $bits will look like:
$bits = array(
0 => 'ENO',
1 => '1000'
)
and then on the next iteration will
$bits = array(
0 => 'ENAME',
1 => 'B'
)
and so on. What you do with those individual chunks is up to you.
And yes, this was all present in the answers of the other questions. You just had to do a bit of work to put it all together.
Yeah, it was.
It's just to say that around that, you have to explode() by ";" and in the loop use Marc's code, since there are multiple Sets of data in the string
Related
This question already has answers here:
How can I explode a string by more than one space, but not by exactly one space in php
(2 answers)
Closed 8 months ago.
I am reading from files and each line has multiple spaces. Example:
$line = 'Testing Area 1 10x10';
I need to convert it into array with 3 elements only so I can save it to a table. Final output should be like this:
$final_array = array('Testing Area', '1', '10x10');
This is how I'm doing it so far:
// read by line
foreach(explode(PHP_EOL, $contents) as $line) {
// split line by 2 spaces coz distance between `1` and `10x10` is atleast 2 spaces
$arr = explode(' ', $line);
// But because `Testing Area` and `1` has so many spaces between them,
// exploding the $line results to empty elements.
// So I need to create another array for the final output.
$final_array = array();
// loop through $arr to check if value is empty
// if not empty, push to $final array
foreach ($arr as $value) {
if (!empty($value)) {
array_push($final_array, $value);
}
}
// insert into table the elements of $final_array according to its column
}
Is there a better way to do this instead of looping through the array and checking each element if it's empty?
Take note that I have multiple files to read, each containing atleast 200 lines like that.
Use preg_split(), with 2 or more spaces as the delimiter.
$array = preg_split('/\s{2,}/', $line);
Assuming the criteria for splitting be two or more spaces, we can try using preg_split here:
$line = 'Testing Area 1 10x10';
$final_array = preg_split("/\s{2,}/", $line);
print_r($final_array);
This prints:
Array
(
[0] => Testing Area
[1] => 1
[2] => 10x10
)
I am a newbie here and I have a php array of some strings, such as {"VAL1","VAL2", "VAL3", "VAL4"} and I have a larger string (normally a text file). The text file contains the elements of the arrays at different positions and some or all may be repeating more than one. Each of of the elements of the array that are contained in the text file are immediately followed by a time of occurence, for example, "VAL1 0900UTC and other text information".The problem now is that I want to find the occurrence(s) of all of the elements of the array in the text file and the time value following the element.
Please note that some of the elements may occur more than once at different positions with different time value in the textfile.
Already, I can load the textfile and get all of the elements.:
$mytextfile = preg_replace('/\s+/', ' ', strtoupper(file_get_contents($textpath."/". $textfile)));
$substr = array("REALTK","BGPTK", "SUDTK", "BECTK");
$bigstring = "REALTK 1000UTC 16/14 1011 BGPTK 1030UTC 10/12 992 REALTK 1145UTC 00/14 2222 SUDTK 1412UTC 11/06 1011 REALTK 1600UTC 16/14 1015 ...";
//I created variables to hold all element occuring to false
$is_val1 = false; $is_val2 = false;$is_val3 = false; $is_val4 = false;
//I created variables to count how many of each substring exist in the string
$numofval1=$numofval2=$numofval3=$numofval4=0;
if(strpos($bigstring, $substr[0]) !== false) {
$is_val1 = true;
//if exist, count how many times
$numofval1 = substr_count(strtoupper($bigstring),$substr[0]);
} e.t.c
I have been able to get the occurrence of each of the array elements in the big string
I have been able to detect if any of the array elements occur more than once in big string and number of times it does.
But I have not being able to get them in the sequence they occur with their position in the textfile string and the time value after each element.
$mytextfile = preg_replace('/\s+/', ' ', strtoupper(file_get_contents($textpath."/". $textfile)));
$substr = array("REALTK","BGPTK", "SUDTK", "BECTK");
//this is a sample content of the textfile
$bigstring = "REALTK 1000UTC 16/14 1011 BGPTK 1030UTC 10/12 992 REALTK 1145UTC 00/14 2222 SUDTK 1412UTC 11/06 1011 REALTK 1600UTC 16/14 1015 ...";
//I created variables to hold all element occuring to false
$is_realtk = false; $is_bgptk = false;$is_sudtk = false; $is_bectk = false;
//I created variables to count how many of each of the element exist in the text file string
$numofrealtk=$numofbgptk=$numofsudtk=$numofbectk=0;
if(strpos($bigstring, $substr[0]) !== false) {
$is_realtk = true;
//if exist, count how many times
$numofrealtk = substr_count(strtoupper($bigstring),$substr[0]);
} e.t.c
What I need is to get the Elements of the array in the order in which they occur in the text file with their position and time value
REALTK POSITION1 1000UTC
BGPTK POSITION5 1030UTC
REALTK POSITION8 1145UTC
SUDTK POSITION13 1412UTC
REALTK POSITION17 1600UTC
I also want to store the element => timevalue as associative array.
Thanks in anticipation.
Here is the snippet for you, please see inline doc for explanation
$substr = array("VAL1","VAL2", "VAL3", "VAL4");
$bigstring = "OTHERS VAL1 VAL4 VAL1 OTHERS OTHERS VAL2 OTHERS";
// considering space to explode words and having numbers in it
$temp = array_unique(str_word_count($bigstring, 1,"0..9"));
// sorting generated array and keeping index of value
asort($temp);
// matching records from array
$temp = array_intersect($temp,$substr);
// showing all the data you want
array_walk($temp,function($item,$k){
echo $item.' POSITION '.$k."\n"; // replace \n with <br/> if web
});
Working demo.
If the elements in your $bigstring are always divided by a whitespace, you can explode:
$val_arr = array( "REALTK" => array(), "BGPTK" => array(), "SUDTK" => array(), "BECTK" => array();
$bigstring_arr = explode( " ", $bigstring);
foreach( $bigstring_arr as $key => $part ){
if( in_array( $part, $substr ) ){
$val_arr[$part][] = array( "position" => $key+1, "time" => $bigstring_arr[$key+1] );
}
}
If it's not you can also explode directly on each element of Val1, Val2... . The code gets a bit more complicated then. But it would work as well if you created a new array in the form of "CountOfAllCharsInBigstringBeforeOccurence" => "KeyOfValInSubstr". From that you can derive your ordering with the vals.
Edit:
I edited the code based on your comment. Please note that it is not possible to have an array that has the same key multiple times which is why the solution here will have multiple dimensions.
To start off, I've read the handful of questions here asking similar questions but nothing that I could take example of and implement properly into my code. I've got an array that hold a few thousand numbers, they're the names of a file in a directory. I need to run a MySQL Query that searches for those file names, but I need all the individual queries to be in another array.
Here's my code to grab the filenames:
$dir = "C:/Users/EyeCandy-Brian/Desktop/jobs";
$files = array_diff(scandir($dir), array('..', '.'));
function truncate(&$fcn) {
$fcn = substr($fcn, 0, 6); // The original is '100100.dat', I only need the number
};
array_walk($files, "truncate");
The array looks like this:
2 => string '100100'
3 => string '100101'
4 => string '100102'
5 => string '100103'
// About 1,500+ Total
And here's my foreach loop with my declared variables:
$limit = 0; // This is for testing, stops after 5 iterations.
$qryArrNum = 2; // The index for the $files array, [0] & [1] were '.' & '..'
$count = 0; // Which index I want to store the string in, starting at [0]
$qry = array(); // I declare $qry as an array
foreach ($files as &$qry) {
$qry[$count++] = "SELECT * FROM `table` WHERE `sku` LIKE '%$files[$qryArrNum]%'";
++$qryArrNum;
if (++$limit == 5) {
break;
};
};
Here's where it gets wild. When using var_dump($qry); I get '1001S4' which shouldn't be. Running var_dump($files); The first five strings of the array are:
2 => string 'S00100'
3 => string '1S0101'
4 => string '10S102'
5 => string '100S03'
6 => string '1001S4'
Then following that are the expected strings from the filenames:
7 => string '100105'
8 => string '100106'
9 => string '100107'
// On for 1,500+ again
So my question is, how do I get $qry to be an array that contains a string, each string being the MySQL Query containing a search for the first value from $files, and the next string in the $qry array will search for the next value from $files. Also, why are the first handful values in $files completely different than what's expected?
NOTE: I understand that running a thousand plus MySQL Queries sequentially will murder my server, I'll use implode(); to combine them into one large query, I just need to figure this out initially.
Instead of running multiple queries you could use the mysql find_in_set().
https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set
Once you have your files, use implode to convert to a string
$tmp = implode(",",$files);
Your sql statement would be:
$sql = "SELECT * FROM `table` WHERE FIND_IN_SET(`sku`,'{$tmp}')>0";
This will return all the matching items
This question already has answers here:
Create a comma-separated string from a single column of an array of objects
(15 answers)
Closed 7 months ago.
I have some WordPress custom fields data that I am looping through and creating a comma separated string. The (small) issue is that I get a warning if I don't set the property as empty / null etc before looping.
I guess you can't concatenate a string if it doesn't yet exist. Although I get the warning, the foreach does what I need an there are no errors.
To stop the warning I have set the property as an empty string to start:
$memlog->postnominals = "";
foreach (get_field('post_nominals', $post->id) as $postnominal) {
$memlog->postnominals .= $postnominal->post_title . ", ";
}
Although not a big issue, I would rather know if there is a way I can do this without setting an empty string?
Don't use concatenation to begin with, join an array, that way you also don't have to strip off the last , afterwards:
$memlog->postnominals = join(', ', array_column(get_field(...), 'post_title'));
array_column only works with objects in PHP 7+, for older versions use a map:
$memlog->postnominals = join(', ', array_map(
function ($p) { return $p->post_title; },
get_field(...)
));
Please use array then implode that data from array to form comma separated string.
Example:
$aa = array(1 => 'a', 2 => 'b', 3 => 'c');
foreach ($aa as $k => $v) {
$b[] = $v;
}
print_r(implode(',', $b));
I have an array which returns something like this:
[44] => 165,text:Where is this city:,photo:c157,correct:0,answers:[{text:Pery.,correct:true},{text:Cuba.,correct:false},{text:Brazil.,correct:false}]},{
I would like to get all the numbers from the beginning of the string until the first occurrence of a comma in the array element value. In this case that would be number 165 and I want to place that number in another array named $newQuesitons as key questionID
Next part will be to get the string after the first occurrence of : until the next occurrence of : and add it into the same array ($newQuestions) as key question.
Next part will be the photo:, that is I need to get the string after the photo: until the next occurrence of the comma, in this case peace of the string extracted will be c157.
I would like to add that as new key named photo in the array $newQuestions
I think this may be able to help you
<?php
$input = '165,text:Where is this city:,photo:c157,correct:0';
//define our new array
$newQuestions = Array();
//first part states we need to get all the numbers from the beginning of the string until the first occurence of a ',' as this is our array key
//$arrayKey[0] is our arrayKey
$arrayKey = explode(',',$input);
//second part requires us to loop through the array and split up the strings by comma and colon
foreach($arrayKey as $data){
//split each text into 2 by the colon
$item = explode(':',$data);
//we are only interested in items that have a colon in them, if we split it and the input has no colon, the count would be 0, so this check is used to ignore those
if(count($item) > 0) {
//now we can build our array
$newQuestions[$arrayKey[0]][$item[0]] = $item[1];
}
}
//output array
print_r($newQuestions);
?>
I don't fully understand the inputted array so the code above will most likely have to be tweaked, but atleast it gives you some logic to go from.
The output of this was: Array ( [165] => Array ( [165] => [text] => Where is this city [photo] => c157 [correct] => 0 ) )
I get my own solution, at least for the part of the problem. I manage to get the questionID using the following code:
$newQuestions = array();
foreach ($arrQuestions as $key => $question) {
$substring = substr($question, 0, strpos($question, ','));
$newQuestions[]['questionID'] = $substring;
}
I am now trying to do the same thing for the question part. I will update this code in case that someone else may have similar task to accomplish.