Exploding string from a json - php

So, my problem is: I capture data from my database, part of this date is inside a json array. Then, I put all of the json information into an array. Like this:
foreach ($corporativos->lista as $value):
$classe_row = '';
$input = $value["info_adicionais"];
$data = json_decode($input,true);
echo $data['andamentos'];
$arr1 = explode(',',$data['andamentos']);
endforeach;
Now, I need to populate a table with this information. But I can't explode the string.
The strings are like this:
" Name name name, 123123/uf; Name name, 123123/uf " and so on.

First trim the string and explode on the ";" sign and on the "," sign as:
$str = " Name name name, 123123/uf; Name name, 123123/uf ";
$str = trim($str);
$temp = explode(";",$str);
if (count($temp) > 0) {
foreach ($temp as $key=>$value) {
$result[] = explode(",",$value);
// OR
$result[whatever the id you want here] = explode(",",$value);
}
}

Related

PHP custom value in json_encode

I have this code for print result for PHP json output:
$value = array();
$return_arr = array();
$row_array = array();
$fileName = Access::FETCH("SELECT name ,id FROM " . TAGS . " GROUP BY name ORDER BY name ASC");
foreach($fileName as $key => $value)
{
$row_array['id'] = $value['id'];
$row_array['text'] = $value['name'];
$rows2[] = $row_array;
}
$ret = array();
echo json_encode($rows2);
result is:
[{"id":406,"text":"404"},{"id":405,"text":"tag1"},{"id":404,"text":"tag3"},{"id":401,"text":"tag4"}]
But in action i see id value not Between ""(example:"id":406) i need to this format for json_encode:
{"id":"405","text":"tag1"}
How do create this?!
First, if you write your query slightly differently then it appears that you do not have to copy the values into a temporary array:
$fileName = Access::FETCH("SELECT id, name AS text FROM " . TAGS . " GROUP BY text ORDER BY text ASC");
json_encode($fileName);
In other words, name AS text just changes the key at the source, so to speak.
As for the integer not being a string. Before you do anything you should consider if it even matters. If it does, then correcting it is as simple as just casting them to strings:
$row_array['id'] = (string) $value['id'];
Or if you use my suggestion of the SQL query then you can just loop over the data and cast it, in place:
foreach ($fileName as & $value) {
$value['id'] = (string) $value['id'];
}
json_encode($fileName);
If you need numeric data to be represented as a string all you have to do is explicitly cast it to a string prior to calling json_encode like this:
$row_array['id'] = (string)$value['id'];
Convert $value['id'] to string should help:
$row_array['id'] = (string)$value['id'];

How to extract comma separated column values from database using php

In my database table there is a column named 'marks' . it contains values like 50,55,67,88,...
Now I need to read this values one by one like - first 50, then 55 and so on. How is it possible using php ?
include("db_connect.php");
$result = mysql_query("SELECT * FROM students ",$con);
while($rows = mysql_fetch_array($result))
{
$mark1=$rows['marks'];//what will do here
$mark2=$rows['marks']; //should get value 55 and so on
}
If your values are comma separated then explode the field.
http://php.net/manual/en/function.explode.php
include("db_connect.php");
$result = mysql_query("SELECT * FROM students", $con);
while($rows = mysql_fetch_array($result)) {
$mark=explode(',', $rows['marks']);//what will do here
foreach($mark as $out) {
echo $out;
}
}
Explode the data from the database. Use the explode function.
Access using indexes
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
$mark1 = $exp[0]; //result is 50
$mark2 = $exp[1]; //result is 55
$mark3 = $exp[3]; //result is 67
}
Or loop using foreach
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
foreach($exp as $mark) {
echo $mark;
}
}
If that row contains ,, the just use explode():
while($rows = mysql_fetch_assoc($result)) {
$mark1 = explode(',', $rows['marks']); // should contain the comma separated values
// in array form
// then loop again
foreach($mark1 as $mark_piece) {
// do something here
}
}
You should use the explode function
$marks = explode(",", $rows['marks']);
foreach($marks as $mark){
//your code to do something with the mark.
}
N.B. explode() function breaks the string into array, it accepts three arguments, first one is the delimiter that specifies where to break the string, second one is the string that needs splitting, and third one is not mandatory but it tells how many array to return.
$str_to_exploade = 'This,string,needs,some,exploiting';
$explode_string = explode(',', $str_to_exploade);
echo '<pre>';
print_r($explode_string);
echo $explode_string[0].'<br/>';
echo $explode_string[1];
More about explode() go to : http://php.net/manual/en/function.explode.php

search array of words in database

I have text :
$a = I wanna eat apple , and banana .
I wanna get every words and punctuation of that sentence :
$b = explode(' ', strtolower(trim($a)));
the result of explode is array.
I have a words table on db that has fields : id, word and typewords all in lowercase. but for punctuation there are no exist in db.
I wanna search every words in db to take the type of words, so the final result that i want to get is :
words/typeofwords = I/n wanna/v eat/v apple/n ,/, and/p banana/n ./.
here's the code :
function getWord ($word){
$i = 0 ;
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
while ($row = mysql_fetch_array($query)) {
$word[$i] = $row['typewords'];
$i++;
}
return $word;
}
echo $b.'/'.getWord($b);
but it doesn't work, please help me, thanks !
Try with this:
function getWord($words){
$association = array();
foreach($words as $word)
{
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
if($row = mysql_fetch_array($query))
$association[$word] = $row['typewords'];
elseif(preg_match('/[\.\,\:\;\?\!]/',$word)==1)
$association[$word] = $word;
}
return $association;
}
$typewords = getWord($b);
foreach($b as $w)
echo $w.'/'.$typewords[$w];
function getWord($word){
// concat the word your searching for with the result
// http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat
$query = mysql_query("SELECT CONCAT(word,'/',typewords) as this_result FROM words WHERE word = '$word' ");
$row = mysql_fetch_array($query);
return $row['this_result']." "; // added a space at the end.
}
// loop through the $b array and send each to the function
foreach($b as $searchword) {
echo getWord($searchword);
}
You assume the function parameter to be an array, but it is a string.
Edit: In your function you treat $word as an array as well as a string. Decide what you want and recode your function.

Removing data from MYSQL that is comma delimited via Get and php

What I am doing is adding values to a mysql table with each value seperated by a comma. And each new value is appended to that last value once again seperated by a comma. Now this is all dynamic. What I am having an issue is on how to remove a selected value and the comma. I am using php and mysql.
I can read the values out with explode and line[value].
table name is values
table consist of id, value, value_array
$value_selected would be a $_GET['value']
value_array is the column that contains all the values seperated by comma.
The database selects from values where the id is equal to the Get value.
Then returns all values in the value_array
I then explode the values and have each value from the value_array read through the for loop and line[value].
the code:
start php
$value_selected = $_GET['value'];
$query = mysql_query("SELECT * FROM values WHERE id='$value_selected'");
while($result = mysql_fetch_assoc($query))
{
$check_values = $result['value_array'];
}
$values = explode(",",$check_values);
$count_values = count($values);
for($counter = 0; $counter < $count_values; $counter++)
{
$line = each($values);
$query = mysql_query("SELECT * FROM values WHERE id='$line[value]'");
while($result = mysql_fetch_assoc($query))
{
echo $result['value'].'<br/>';
}
}
php end
I don't have an issue reading it out. What I'm trying to do is being able to select a value via GET and remove that value from the value_array while also removing the trailing comma. I hope I was able to expalin in more detail my issue.
Use a foreach loop, take the exploded string and reassemble it minus the string $value_selected by doing this:
$NewValue = '';
$i = 1;
foreach ($values as $Value) {
if ($i > $count_values) {
break;
} else {
if ($Value !== $value_selected) {//reassemble comma-sep string - $_GET['value']
$NewValue = $NewValue . $Value . ",";
}
}
$i++;
}
Now $NewValue no longer contains $_GET['value'], because the concatenation in the if statement only occurs when the exploded fragment $Value does not match $_GET['value']. Update the database or echo $NewValue, etc. as necessary at this point.

how to parse a column in mysql table like " <14-abc>;<8-def>;

how to parse a column in mysql table like <14-abc>;<8-def>;
as:
abc =14
def = 8
abc store value 14 and def stores values 8 and have multiple entries.
So need to store like array or list that should be able to access and
process the parsed data later.
I'm not aware of any parser that support this syntax, so you could write your own parser for something so trivial. Here's an example, not tested:
$row = ' <14-abc>;<8-def>; ';
$output = Array();
$entries = explode(';', $row); //Split the row by every ';' delimiter
foreach ($entries as $item) { //For each entries
if (!empty($item)) { //Make sure the item isn't empty (last entry might be)
$item = str_replace(' ','',$item); //Remove useless char
$item = str_replace('<','',$item); //Remove useless char
$item = str_replace('>','',$item); //Remove useless char
$params = explode('-', $item); //Again, subsplit the key and the value from the item
$output[$params[1]] = $params[0]; //Push them into an array
}
}
Then you can use your awesome array like so:
foreach ($output as $key=>$value) {
echo $key.'='.$value;
}
The input is a $row string, the output is a $output array. You can even wrap it into a function ;)
?php
function parser($row)
{
$output = Array();
$entries = explode(';', $row); //Split the row by every ';' delimiter
foreach ($entries as $item) { //For each entries
if (!empty($item)) { //Make sure the item isn't empty (last entry might be)
$item = str_replace(' ','',$item); //Remove extra char
$item = str_replace('<','',$item); //Remove extra char
$item = str_replace('>','',$item); //Remove extra char
$params = explode('-', $item); //Again, subsplit the key and the value from the item
$output[$params[1]] = $params[0]; //Push them into an array
}
}
foreach ($output as $key=>$value) {
$sql1 = "INSERT INTO `tablename`(`column name`, `column name`) VALUES ('$key','$value')";
mysql_query($sql1);
}
}
?>
This does all the work.. Defines parser function , parses data and inserts the result in DB

Categories