I have part of a code:
$array = (json_encode($data, true));
which gives me a result of:
"["Id\tFirstName\tLastName\tDateOfBirth\tPhone\tAddress1\tAddress2\tCity\tState\tPostCode\tCountry\tEmail"]"
I need to post it in a filed of a database but it looks harder to view and read.
I would want to get result like
"{Id, FirstName , LastName, DateOfBirth, ...}"
It tried some functions like array_implode, array_replace but no success.
My $data content:
array:1 [
0 => "Id\tFirstName\tLastName\tDateOfBirth\tPhone\tAddress1\tAddress2\tCity\tState\tPostCode\tCountry\tEmail"
1 => "Id\tAnna\tGreen\t199/12/12\t25413698\tMemoryLane\t..."
]
What can I try?
1.if you want results to be array of json strings
$results = [];
foreach($data as $dat){
$results[] = json_encode(explode("\t", $dat));
}
var_dump($results);
2.if you want all results to be json string
$results = [];
foreach($data as $dat){
$results[] = explode("\t", $dat);
}
var_dump(json_encode($results));
Old answer -> Before encoding, explode first value od array (string) by '\t' and after that encode array.
$data = explode("\t", $data[0]);
$results = json_encode($data);
// Example data
$data = array(
"Id\tFirstName\tLastName\tDateOfBirth\tPhone\tAddress1\tAddress2\tCity\tState\tPostCode\tCountry\tEmail",
"May\tBe\tMore\tLines\tHere"
);
// Processing
$a = $data;
// Change all \t to comma and put { } around in each item
array_walk($a, function(&$item) { $item = '{ ' .str_replace("\t", ', ', $item) . ' }'; });
// combine all items into a line
$result = implode(', ', $a);
print($result);
// { Id, FirstName, LastName, DateOfBirth, Phone, Address1, Address2, City, State, PostCode, Country, Email }, { May, Be, More, Lines, Here }
Related
A minimal sample array to represent the relevant portion of my query's result set:
[
['keyw' => 'sam , ram,shyam'],
['keyw' => 'sam,ram,shyam, mohan'],
['keyw' => 'sam, ram, shyam ,mohan,salman,babu , karan'],
]
I want to remove duplicate names to get an output like
[
sam,
ram,
shyam,
mohan,
salman,
babu,
karan
]
How can I achieve this?
<?php
include 'config.php';
$db = new Database();
$db->select('post','*',null,null,'id',20);
$result = $db->getResult();
if (count($result) > 0) {
foreach ($result as $row) {
$string = $row['keyw'];
$string = $string;
$array = explode(',', $string);
print_r(array_merge($array));
}
}
?>
You can use array_unique function for removing duplicate array values.
Like $arrayWithUniqueValues = array_unique($OriginalArray);
Because these seem like separate arrays, you can merge these first with array_merge, like: array_merge($array1, $array2).
The new array should only contain unique values then.
<?php
include 'config.php';
$db = new Database();
$db->select('post','*',null,null,'id',20); $result = $db->getResult(); if(count($result) > 0){
$newArray = array();
foreach ($result as $value) {
$sh_genres = $value['keyw'];
$sh_genres_array = array_map('trim', explode(',',$sh_genres));
$newArray = array_merge($newArray , $sh_genres_array );
}
$newUniqueArray = array_unique($newArray);
foreach($newUniqueArray as $links) {
echo '<p>'.$links.'</p>';
}}?>
You can split your column values on commas and consume the potential leading and trailing spaces around commas with preg_split(), then flip the values when pushing data into the result array to ensure uniqueness. Then when you want access the unique values, you can use array_keys() to convert the keys to values.
Code: (Demo)
$unique = [];
foreach ($db->getResult() as $row) {
$unique += array_flip(preg_split(
'/ *, */',
$row['keyw'],
0,
PREG_SPLIT_NO_EMPTY
));
}
var_export(array_keys($unique));
I have a string and I would want to get the values/fields from it. However, the values are # separated.
Also, from one copy to the next it is comma separated.
As shown below;
$transaction = "
[2018-01-10 12:50:07.822#SAMUEL#TITUS],
[20120605152613#KEN#NAUGH],
[20120705152645#JOHHY#BRAVO]";
I need to loop through this string getting the values separated by the # for one record the to the next record separated by a comma.
The order of the fields is [TIME#FIRST_NAME#SECOND_NAME].
I can't think of a way to get this done.
Anyone?
Use explode to parse string into array
<?php
$transaction = "[2018-01-10 12:50:07.822#SAMUEL#TITUS],[20120605152613#KEN#NAUGH],[20120705152645#JOHHY#BRAVO]";
$parsed = explode(",", $transaction);
foreach($parsed as $val){
$val = explode("#", $val);
$first_name = $val[1];
$last_name = str_replace("]", '', $val[2]);
echo $first_name." ".$last_name."<br>"; // get firstname & lastname
}
?>
You can use the following solution using explode and array_map:
$transaction = "
[2018-01-10 12:50:07.822#SAMUEL#TITUS],
[20120605152613#KEN#NAUGH],
[20120705152645#JOHHY#BRAVO]";
//normalize the string and remove the unnecessary chars.
$transaction = str_replace(['[', ']', "\n"], '', $transaction);
//get all the rows as array.
$rows = explode(',', $transaction);
//create the columns in rows.
$row_arr = array_map(function ($row) {
return explode('#', $row);
}, $rows);
//info of the first row.
echo $row_arr[0][0]; // time
echo $row_arr[0][1]; // firstname
echo $row_arr[0][2]; // lastname
//run through the rows to output.
foreach ($row_arr as $row_item) {
echo 'Time: '.$row_item[0].', Firstname: '.$row_item[1].', Lastname: '.$row_item[2]."<br>";
}
demo: https://ideone.com/3uYcSw
This question already has answers here:
Better way to check variable for null or empty string?
(11 answers)
Closed 8 months ago.
Let's say hypothetically I have this information listed on each users profile:
UserA (list) = dog, cat, sheep, bird, duck
UserB (list) = zebra, lion, cheetah, leopard
UserC (list) = alligator, lizard, frog, turtle
and I have this function:
foreach($users as $user){
$user_list = $user->list;
$user_list_array = explode(', ', $user_list);
foreach($user_list_array as $user_list_item){
}
}
}
This is where I'm stumped... How do I combine all the lists into one big comma separated list and explode that full list into one array that I can then use?
EDIT: Here are the exact sample lists I'm testing with and the results I'm getting with the following code:
THE LISTS:
ListA: Singing, Rapping, Dancing, Comical Skits, Cooking, Cleaning, Shoe-Tying, Hop on No Legs
ListB: Wine Tasting, Hospitality, Business Management, Financial Planning, Business Marketing, Professional Driving
THE CODE:
<?php
$roles = array('employee', 'administrator');
/* Loop through users to search for the admin and employee users. */
foreach( $roles as $role ) {
$this_role = "'[[:<:]]".$role."[[:>:]]'";
$query = "SELECT * FROM $wpdb->users WHERE ID = ANY (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = 'wp_capabilities' AND meta_value RLIKE $this_role) ORDER BY user_nicename ASC LIMIT 10000";
$users = $wpdb->get_results($query);
if ($users){
$output = array();
foreach($users as $user){
$curuser = get_userdata($user->ID);
$user_list = $curuser->skills;
$user_list_array = explode(', ', $user_list);
foreach($user_list_array as $user_list_item){
$output[] = $user_list_item;
}
}
echo implode(', ', $output);
}
}?>
THE RESULT:
Singing, Rapping, Dancing, Comical Skits, Cooking, Cleaning, Shoe-Tying, Hop on No Legs, , , , , , Wine Tasting, Hospitality, Business Management, Financial Planning, Business Marketing, Professional Driving
How do I combine all the lists into one big comma separated list and explode that full list into one array that I can then use?
That's a long winded process of doing this:
$output = array();
foreach($users as $user){
$user_list = $user->list;
$user_list_array = explode(', ', $user_list);
foreach($user_list_array as $user_list_item){
$output[] = $user_list_item;
}
}
echo implode(', ', $output); // your combined results
But why not simplify it and just concatenate the results you want for each array?
$output = '';
foreach($users as $user) {
$output .= $user->list;
}
// this doesn't use arrays at all
echo $output;
... or better yet (as far as structured data goes), merge the arrays:
$output = array();
foreach($users as $user) {
$bits = explode(', ', $user->list);
$output = array_merge($output, $bits);
}
// this is a simplified step from your first example
echo implode(', ', $output);
Edit
Updating based on your output with lots of this: ,,,,,, - chances are you have blank fields in your database. You're still adding those to the array and they're still being comma seperated. I'd suggest this:
foreach($user_list_array as $user_list_item){
if(trim($user_list_item) != '')
$output[] = $user_list_item;
// only add the item if it's not blank (after trimming potential whitespace off)
}
Edit : Is there any way to input a comma where the first list stops and next list starts?
Of course, either add it after the inner foreach loop using the [] structure to add a new array item like this:
$output[] = PHP_EOL; // or \n newline, or a space, or whatever you want to seperate your sets as well as a comma
... or the better way (structurally) would be to create a multi dimensional array and implode it at the end;
$output = array();
foreach($users as $user){
$temp_output = array();
$curuser = get_userdata($user->ID);
$user_list = $curuser->skills;
$user_list_array = explode(', ', $user_list);
foreach($user_list_array as $user_list_item){
if(trim($user_list_item) != '')
$temp_output[] = $user_list_item;
}
$output[] = implode(', ', $temp_output);
}
// put your set delimiter here, whether it's a comma, |, \n, PHP_EOL, whatever
echo implode(', ', $output);
$bigArray = array();
foreach($users as $user){
$user_list = $user->list;
$user_list_array = explode(', ', $user_list);
foreach($user_list_array as $user_list_item){
$bigArray[] = $user_list_item;
}
}
$all_user_list_array = array();
foreach($users as $user){
$user_list = $user->list;
$user_list_array = explode(', ', $user_list);
$all_user_list_array = array_merge($all_user_list_array, $user_list_array);
}
$all_user_list = implode(', ', $all_user_list_array);
I'm basically creating one big array of all the list items and then packing it down in to an array, splitting each value by a comma.
It might be worth asking exactly what you are trying to achieve? There are better ways of storing data than comma separated strings. These string can take a while to process as they need to be tokenised. However, I appreciate you may have your own use cases.
This will give you a complete list with unique values (no duplicates from mulitple lists). I assumed that with UserA (list) you have an array of users with a user object.
$complete_list = array();
foreach( $users as $user )
{
$list = explode( ",", $user->list );
foreach( $list as $k=>$item ) $list[$k] = trim( $item );
$complete_list = array_merge( $complete_list, $list );
}
If your users array is an array, this is the solution:
$complete_list = array();
foreach( $users as $user )
{
$list = explode( ",", $user['list'] );
foreach( $list as $k=>$item ) $list[$k] = trim( $item );
$complete_list = array_merge( $complete_list, $list );
}
Say I have a String 030512 Jack 25 Male\n030513 David 23 Male\n030514 ..., how to extract the info from this String as a two dimensional table in PHP?
In Java, I can use StringTokenizer, like:
StringTokenizer lineTokenizer = new StringTokenizer("030512 Jack ...", "\n");
List<Student> students = new ArrayList<Student>();
while(lineTokenizer.hasMoreTokens()) {
String line = lineTokenizer.nextToken();
StringTokenizer itemTokenizer = new StringTokenizer(line, " ");
String id = itemTokenizer.nextToken();
String name = itemTokenizer.nextToken();
String age = itemTokenizer.nextToken();
String sext = itemTokenizer.nextToken();
students.add(new Student(id, name, age, sex));
}
Actually, my final goal is extracting this "table-like" info and store them into a Mysql database.
I am not familiar with PHP, could you show me how to do this in PHP, or what is a good practice to implement this two-dimensional data insertion into a Mysql database?
You can use the explode or split functions. E.g.
$records = explode("\n", $raw_data);
foreach($record in $records) {
$fields = explode(" ", $record);
$id = fields[0];
$name = fields[1];
///....
}
Not fancy but easier to understand in my opinion (requires that the string doesn't end with newline though, and that the information is always correctly formatted):
$students = array();
//no newline at the end, or you'll have to add a check for that in the loop.
$str = "030512 Jack 25 Male\n030513 David 23 Male";
foreach(explode("\n", $str) as $student_str) {
list($id, $name, $age, $sex) = explode(" ", $student_str);
array_push($students, array(":id"=>$id,":name"=>$name, ":age"=>$age, ":sex"=>$sex));
}
//For the DB part which has been quite absent.
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$query = "INSERT INTO students (id, name, age, sex) VALUES (:id, :name, :age, :sex)";
$prepared_query = $conn->prepare($query);
foreach($students as $student) {
$prepared_query->execute($student);
}
You could of course execute the queries in the first loop instead if thats what you want.
You can use explode() coupled with list():
foreach (explode("\n", $yourString) as $line) {
list($id, $name, $age, $sex) = explode(' ', $line);
// ...
}
Edit:
Updated the solution to correct a misunderstanding of the original data structure.
You could do like this
$string = "030512 Jack 25 Male\n030513 David 23 Male\n030514";
$array = array_map(function($v) {
return explode(' ', $v);
}, explode("\n", $string));
How i can insert in database from textarea field that each line is a table in database
means I want insert in database from each line of textarea field by php
my information like this:
Name | FullName | Age
and database table:
id (auto insert),
name,
fullname,
age
thanks
i would suggest using a delimiter at the end of the line and then convert it into an array using explode(), here is what you could do.
//Make sure your text have (,) comma at the end of every line
$text = 'My Name,
My Full Name,
24';
//Convert it into an array
$text = explode(',', $text);
//fetch the value and assign it to variables then do an insert operation
//Use mysql_real_escape_string() to escape SQL injections.
$name = mysql_real_escape_string($text[0]);
$FullName = mysql_real_escape_string($text[1]);
$age = mysql_real_escape_string($text[2]);
and then you can create query like this.
$query = "INSERT INTO persons(name, fullName, age) values($name, $fullName, $age)";
$result = mysql_query($query);
// assuming the text area value is in $_GET["text"]
$lines = explode("\n", $_GET["text"]);
foreach($lines as $line) {
list($name, $fullName, $age) = explode(" | ", $line);
mysql_query("INSERT INTO table (name, fullname, age) VALUES ('$name', '$fullName', $age)");
}
Hope this helps:
// assuming textarea name is $_POST['data']
$_POST['data'] = 'Jane | Jane Doe | 23
zxc
sadas
John | John Doe | 48
';
// Set and trim data
$data = (array_key_exists('data', $_POST)) ? trim($_POST['data']) : '';
if ($data !== '') {
$lines = explode("\n", $data);
$sql = 'insert into table (name, fullname, age) values ';
$sql_parts = array();
foreach ($lines as $line) {
$sql_part = array(
'name' => null,
'full_name' => null,
'age' => null,
);
// If no divider found, skip this line
if (strpos($line, ' | ') === false)
{
continue;
}
list($sql_part['name'], $sql_part['full_name'], $sql_part['age']) = explode(' | ', $line);
// For the sake of this example
// i will assume all fields are required
// so let's check for that:
foreach ($sql_part as $key => $item) {
// Trim and sanitize the data:
$item = mysql_real_escape_string(trim($item));
// If any item is empty continue to the next line of data
if ($item === '') {
continue 2;
}
$sql_part[$key] = "'".$item."'";
}
$sql_parts[] = '('.implode(',', $sql_part).')';
}
if (empty($sql_parts) === false) {
$sql .= implode(',', $sql_parts);
mysql_query($sql);
}
}
Split the string, for example http://php.net/manual/en/function.explode.php