I know its a strange question, but I have one input field that does a live search for locations. The final value is displayed like this:
State,Suburb,Post Code
NSW,Sydney,2210
What I need to do now is split the three values into single values and update them into my separate fields for one row.
I don't want to update multiple rows but just one.
e.g.:
fields ( state | suburb | postcode )
values ( NSW | sydney | 2210 )
What php commands would I use to split those commas off and create single $values for each item?
Use explode on the string.
$values = 'A,B,C,D';
$values = explode(',', $values);
Each item can then be accessed from an array indexed from 0.
$val = "NSW,Sydney,2210";
$valArr = explode(",", $val);
$query = "UPDATE MyTbl SET State = '$valArr[0]', Suburb = '$valArr[1]', Post_Code = '$valArr[2]' WHERE ...";
The easiest way I think, see the manual for explode:
$result_array = explode(',', $your_variable);
list($state, $suburb, $postcode) = explode(',', $value);
Would this work?
$header = "State,Suburb,Post Code"
$items = explode(",", $input)
$output = implode("|", $items)
so the output would become State|Suburb|Post Code
to access each value separately, you can use $items[0], $items[1] ..
$data = "NSW,Sydney,2210"
$items = explode(",", $input)
$output = implode("|", $items)
so the output would become NSW|Sydney|2210
Related
I am a newbie in this and I have read lots of stuff about this matter (including some topics here), before starting this topic, but I do not quite get it yet, so I will ask for some help (if it is possible) :)
So, in the column that I want to print I have values like this on every row:
value1|value2|value5|value12|value25
value3|value5|value12|value14|value26|value32|value55
value1|value2|value14|value26|value31
The number of rows can be 3 or 1500+... So I want to merge the arrays and print those values sorted and without duplicates: value1, value2, value3, value5, value12, etc...
I have tried to explode the arrays, but I could not find out how to assign a variable to every array and merge them and all I have done is to print all values:
foreach ($rows as $areas) {
foreach (explode('|', $areas->value) as $area) {
var_dump($area);
}
}
Afterwards I have read somewhere this will be very slow if I have many rows (and I am going to have thousands), so I am stuck here and I do not know what else I could do...
I will appreciate any help and direction that you can give me, because it is too hard for me and I can not do it without help
Thank you in advance
You can store each value of your exploded string as key (if it's not an object nor array), it store only unique values. Then you have to just use array_keys() to get keys and sort returned array:
$rows = array(
'value1|value2|value5|value12|value25',
'value3|value5|value12|value14|value26|value32|value55',
'value1|value2|value14|value26|value31'
);
$results = array();
foreach ($rows as $row) {
$items = explode('|', $row);
foreach ($items as $item) {
$results[$item] = 0;
}
}
$results = array_keys($results);
sort($results, SORT_NATURAL);
Live demo on eval.in
There are two ways of doing this:
<?php
$str = 'value1|value2|value5|value12|value25';
$str1 = 'value3|value5|value12|value14|value26|value32|value55';
$str2 = 'value1|value2|value14|value26|value31';
//-- Method 1: Concat and make a single string and then explode and make a single array
$finalString = $str . '|' . $str1 . '|' . $str2;
print_r(array_unique(explode('|', $finalString)));
//-- Method 2: explode first and then merge into a single array
$strArr = explode('|', $str);
$strArr1 = explode('|', $str1);
$strArr2 = explode('|', $str2);
print_r(array_unique(array_merge($strArr, $strArr1, $strArr2)));
I have a sting that looks like this
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
I want to break out selected companies and the number of locations by comparing the first string to a second string like
$selectedstores = "‘F Mart’, 'J/M Store";
And output a sting like
$selectedwithnumber = "‘F Mart (6)’, 'J/M Store (17)'"
There could be 1 to 15 companies in a string and the location number varies but the apostrophes and parenthesis are standard. I hope there an easy way to do this as I have no idea where to start. Thanks in advance.
You can use explode function to split arrays to parts, and use preg_replace function to remove number of companies (with brackets) from first string. below you can find working example:
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
$selectedstores = "‘F Mart’, 'J/M Store'";
//split second array
$selectedArray = explode(', ', $selectedstores);
$resultArray = array();
//split first array
foreach(explode(', ', $storelist) as $storeWithNumber) {
//remove " (number)" from each part
$store = preg_replace('/\s+\(\d+\)/', '', $storeWithNumber);
//check if current part is on selected list
if (in_array($store, $selectedArray)) {
$resultArray[] = $storeWithNumber;
}
}
$selectedwithnumber = implode(', ', $resultArray);
echo $selectedwithnumber.PHP_EOL;
result is:
‘F Mart (6)’, 'J/M Store (17)'
This will get what you need based on your description. It breaks up your strings into arrays and then uses a nested foreach loop to do the comparisons. I used string functions over regular expression functions in case speed becomes an issue. It does however require that your main string of stores follows the conventions you described.
<?php
$storelist = "'F Mart (6)', 'ACME (5)', 'J/M Store (17)'";
$selectedstores = "'F Mart', 'J/M Store'";
$stores = explode(",", $storelist);
$selected = explode(",", $selectedstores);
$newStoreList = array();
foreach($selected as $selectedStore) {
foreach($stores as $store) {
$s = trim( $selectedStore, "' ");
if(strstr($store, $s)) {
$newStoreList[] = $store;
}
}
}
$newStoreList = implode(",", $newStoreList);
echo $newStoreList;
?>
This will output: 'F Mart (6)', 'J/M Store (17)'
Hope that helps!
I have two arrays, one containing the field names which are imploded into a string called $fields, and one containing the data imploded into $data.
When data is first entered using the INSERT command the query looks like...
mysql_query("UPDATE table ($fields) VALUES ($data)")
(BTW: all data is sanitised)
My goal is to build a mysql UPDATE statement where the syntax is
mysql_query("UPDATE table SET $field1=$data1, $field2=$data2 ...")
and update all fields at once, so I need to combine the two arrays to build the alternating field/data/field/data structure instead of all of the fields followed by all of the data.
My idea is to use array_combine or array_merge and then implode into a string that will then set the function to
mysql_query("UPDATE table SET $imploded-combined-arrays")
I recognise that this won't work as the "glue" of the implode statement has two different values depending upon whether it is equating or separating field/data pairs.
How can I step through both arrays and build a string that is appropriate for the UPDATE syntax?
Thanks,
Cam
Try this
$a = array('key1', 'key2', 'key3');
$b = array('value1', 'value2', 'value3');
$c = array_combine($a, $b);
foreach($c as $key=> $value){
$result[]=$key."='". $value."'";
}
$updatefields= implode (', ', $result);
echo ("update table set " .$updatefields);
OUTPUT
update table set key1='value1', key2='value2', key3='value3'
DEMO
$names = array ('foo', 'bar');
$values = array ('hello', 'world');
$pairs = array ();
foreach ($names as $i => $name)
{
$value = $values [$i];
// $name = mysql_real_escape_string ($name);
// $value = mysql_real_escape_string ($value);
$pairs [] = "`$name` = '$value'";
}
echo ("UPDATE t SET " . implode (', ', $pairs));
For me outputs is:
UPDATE t SET `foo` = 'hello', `bar` = 'world'
I have a loads of numbers in a string
$userlist = '12,17,46,35,32,66,43,64'; //the userlist can be as long as i want
$arr2 = explode(',', $userlist);
i dont now how to get them to output like the follow.
12,17
46,35
32,66
43,64
Thank You for taking the time to read.
You can use array_chunk to group two together again and then iterate over the groups and implode each again with the ,. Example (Demo):
$userPairings = array_chunk($arr2, 2);
foreach ($userPairings as &$pair)
{
$pair = implode(',', $pair);
}
unset($pair);
echo implode("\n\n", $userPairings);
Output:
12,17
46,35
32,66
43,64
I have an array holding this data:
Array (
[1402377] => 7
[1562441] => 7
[1639491] => 9
[1256074] => 10
)
How can create a string that contains the keys of the above array?
Essentially, I need to create a comma separated string that consists of an array's keys
The string would look like: 'key','key','key'
Do I need to create a new array consisting of the keys from an existing array?
The reason I need to do this is because I will be querying a MySQL database using a WHERE in () statement. I would rather not have to query the database using a foreach statement. Am I approaching this problem correctly?
I've tried using a while statement, and I'm able to print the array keys that I need, but I need those keys to be an array in order to send to my model.
The code that allowed me to print the array keys looks like this:
while($element = current($array)) {
$x = key($array)."\n";
echo $x;
next($array);
}
$string = implode(',', array_keys($array));
By the way, for looping over an array consider not using current and next but use foreach:
foreach ($array as $key => $value) {
//do something
}
This will automatically iterate over the array until all records have been visited (or not at all if there are no records.
$keys = array_keys($array);
$string = implode(' ',$keys);
In your case, were you are using the result in a IN clause you should do:
$string = implode(',', $keys);
$yourString = '';
foreach($yourArr as $key => $val) {
$yourString .=$key.",";
}
echo rtrim($yourString, ",");
//OR
$yourString = implode(",", array_keys($yourArray));
See : array_keys
implode(', ', array_keys($array));
Use php array_keys and implode methods
print implode(PHP_EOL, array_keys($element))
The string would look like: 'key','key','key'
$string = '\'' . implode('\',\'', array_keys($array)) . '\'';
Imploding the arguments and interpolating the result into the query can cause an injection vulnerability. Instead, create a prepared statement by repeating a string of parameter placeholders.
$paramList = '(' . str_repeat('?, ', count($array) - 1) . '?)'
$args = array_keys($array);
$statement = 'SELECT ... WHERE column IN ' . $paramList;
$query = $db->prepare($statement);
$query->execute($args);