How to retrive comma seaparated values from database? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to retrieve comma separated values from a database and store each value in a variable.
For example: in my column I have the following: 2,3,5,8,9,21
I'd like to store the numbers inside variables like this:
$a=2
$b=3
$c=5
// and so on…

If you wanna load the string that contain integers separated with ',' or '.' or 'a' or ';' do:
If you wanna go for ',':
$char = ',';
If you wanna go for '.':
$char = '.';
If you wanna go for 'a':
$char = 'a';
If you wanna go for ';':
$char = ';';
(I added this to help anyone that have any other syntax of string)
To connect you can do(Documentation):
$connection = mysql_connect('adress', 'mysql_user', 'mysql_password');
Okay, we have connection. Now take the data (Documentation).
$database = "DatabaseWithTableWithIntegers";
$table = "TableWithIntegers";
$rowname = "RowWithIntegers";
$sql = "USE $database; SELECT $rowname FROM $table;";
$result = mysql_query ($sql, $connection);
Now declare something like list:
$arr = []; // array for fetching
$vrr = []; // array for fetched
Next step is to fetch rows(Documentation):
while($row = mysql_fetch_row($result)){
Row have string like "2,142,124,53,3511,513,531,53" if separator was an "," and the record exists in database/table.
The magical function is explode, it slices all the segments into an array(Documentation):
$arr = explode($char, $row[$rowname]); //rowname is to be 100% sure
The last thing is to do the conversion(Documentation)
for($arr as &$a){
$value = intval($a);
array_push($vrr, $value); // to save the value into vrr([Documentation][6])
}}

have a look on below solutions:
Method 1
$alphabet = range('a', 'z');
$str = '2,3,5,8,9,21';
$str_array = explode(',', $str);
foreach($str_array as $k=>$v){
${$alphabet[$k]} = $v;
}
echo $a,$b,$c,$d;
Method 2
$var = 'a';
$str = '2,3,5,8,9,21';
$str_array = explode(',', $str);
foreach($str_array as $k=>$v){
${$var} = $v;
++$var;
}
echo $a,$b,$c,$d;
both solution's output:
2358

if you are storing data in form of a1,a2,a3 in a single column, why don't you just fetch the data and split it using explode() method?
if you are using associative array, then use json_encode() when storing the data as string, and then decode it using json_decode() after fetched from database

Related

Duplicate words in PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have probably information about whether it is available in PHP to detect a duplicate and a book about not removing it and adding it to -1, -2, -3
Example:
$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';
Result:
$output = 'H4,H4-1,H3,WY21W,W5W,W5W-1,WY21W-1,W21/5W,W21/5W-1,W21W,W16W,W5W-2'
$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';
$parts = explode(',', $string); // split by comma
$used = []; // array to count the number of occurrences
$result = []; // array to take the "new" elements
foreach($parts as $part) {
if(isset($used[$part])) { // if there is an entry in the counter array already,
// increment it by one,
$used[$part]++;
}
else { // else initialize with 0
$used[$part] = 0;
}
// put part into new array, append -(counter) if counter > 0
$result[] = $part . ($used[$part] ? '-'.$used[$part] : '');
}
echo implode(',', $result); // join together with comma
Pretty much the same as misorude's answer.
<?php
$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';
$values = explode(',', $string);
foreach($values as $k => $value)
if($counts[$value] = !isset($counts[$value]) ? 0 : $counts[$value]-1)
$values[$k] = $value . $counts[$value];
print implode(',', $values);
Output:
H4,H4-1,H3,WY21W,W5W,W5W-1,WY21W-1,W21/5W,W21/5W-1,W21W,W16W,W5W-2

Merge given field value of all rows in one and send in json array php [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am facing a problem.
My table contain a field named 'tags'.
This field have comma separated values.
For ex: Hello, start, good & another one is: Time, Goal, Lucky, start.
Now my problem is that, I want to send each comma separated values in json array
and none of them should repeat itself.
My array should be like this:
{
"tag":[
"Hello",
"start",
"good",
"Time",
"Goal",
"Lucky"
]
}
Just do this with your code.
Assuming $tag_string has the comma separated data.
<?php
$tag_string= "Hello, start, good, Time, Goal, Lucky, start";
$val['tag'] = explode(",", $tag_string);
$val['tag'] = array_unique($val['tag']);
echo json_encode($val);
?>
As you asked in comment answer::
<?php
$tag_string = "Hello, start, good, Time, Goal, Lucky, start";
$val = explode(",", $tag_string);
$val_count = count($val);$html = "[ ";$counter = 1;$data_validate = [];
foreach ($val as $val_row)
{
if (!in_array($val_row, $data_validate))
{
$data_validate[] = $val_row;
$html .= '{"tag":"' . $val_row . '"}';
$html .= $counter < $val_count-1 ? ',' : '';
}
$counter ++;
}
$html .= " ]";
echo $html;
?>
Use a regexp to make à php array then just use jdon_encode() on your array.
You can also use php explose() function to make your php array.
use json_encode(explode(', ', "Hello", "start", "good", "Time", "Goal", "Lucky"));
if you don't have space in your string.
split String using delimiter "," using explode() and remove duplicate value array_unique.
$your_str = "Hello,start,good,Time,Goal,Lucky"
$res["tag"] = array_unique(explode(",", $your_str));
print_r(json_encode($res));
<?php
$tag_string= "Hello, start, good, Time, Goal, Lucky, start";
$result = [];
$result['tag'] = array_unique(preg_split('/\s*,\s*/', $tag_string, NULL, PREG_SPLIT_NO_EMPTY));
echo json_encode($result);

Separate column with comma [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i can separate join column with comma, but how to remove comma if on the second column is null?
in below, i have 2 column i want join otot2 and otot3
1. how to not shown comma after otot2 if otot3 null?
2. and how to not shown anything comma if otot2 and otot 3 null?
3. otot2 and otot3 flexible ( not always has data)
here my php code for output query:
if(mysqli_num_rows($hasil) > 0)
{
$response = array();
while($data = mysqli_fetch_array($hasil))
{
$h['main muscle'] = $data['otot1'];
$h['other muscle'] = $data['otot2'].', '.$data['otot3'];
array_push($response, $h);
}
$response["success"];
echo json_encode($response);
A simple solution would be -
$response = array();
while($data = mysqli_fetch_array($hasil))
{
// other code
$temp = array($data['otot2'], $data['otot3']); // Store them in array
$temp = array_filter($temp); // remove empty values
$h['other muscle'] = implode(',', $temp); // implode them with (,)
// Other codes
array_push($response, $h);
}
By using array_filter & implode you don't have to worry about the ,, as array_filter would remove the empty values and if there is 2 values in the array them the string would be , separated else not.
Or you can try this also
$h['other muscle'] = $data['otot2'];
if($data['otot3'] !== null)
$h['other muscle'] .= ', ' . $data['otot3']; // Concatenate
Demo

How to merge multiple arrays in array without duplicates

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)));

How to explode row in table? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have these row in table
K04, K84, K53, K331, L985
how i can do with array explode to get result like :
['K04','K84','K53','K331','L985']
thanks for any help...
i tried to using explode,
$ex = explode (' ,' $myRowFromTable)
$co = count ($ex);
for ($i = 0; $i < $co; $i++)
{
echo $ex[$i];
}
result only show K04
Seems like you want to convert String to JavaScript Array. Take a look for Example;
$myRowFromTable = 'K04, K84, K53, K331, L985';
// Has Array Data
$ex = explode (', ', $myRowFromTable);
// print_r($ex);
// According to User Expected Result
$newFormat = "['" . implode("', '", $ex) . "']";
echo $newFormat;
DEMO
You should try using explode as below assuming you are getting the values as a string in $myRowFromTable:
$ex = explode (',', $myRowFromTable); //no space before comma

Categories