Get comma seperated values from PHP array - arrays

Do we have any array function in PHP to get this:
// get all the user ids as comma seprated.
$users = array();
foreach($view as $result)
{
$users[] = $result->uid;
}
$uid = implode(',', $users);
Example:
$array[0] = array("size" => "XL", "color" => "gold");
$array[1] = array("size" => "XLL", "color" => "siver");
$array[2] = array("size" => "M", "color" => "purple");
I need
$color = "gold,silver,purple";
Thanks in Advance for your help.

You can use explode(',', $view) in order to get the values array.

From your updated question:
You could try something like this:
'firstname_value','lastname'=>'lastname_value');
sprintf('INSERT INTO %s (%s) VALUES ("%s")', 'table_name', implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values)));
//that gives you: INSERT INTO table_name (firstname, lastname) VALUES ("firstname_value", "lastname_value")
?>

Related

Remove everything before the dash from a Laravel array

I have a Laravel array and would like to modify the returned values.
$array = ['hr-34', 've-53', 'dv-65'];
I want to remove everything before the dash and the dash itself and return the following array.
$array = ['34', '53', '65'];
You can do something like this:
foreach ($c as $key => $value) {
$pieces = explode('-', $value);
$array[$key] = $pieces[1];
}
You have used the tag collections. So if it's a collection you can use this function:
$c->map(function ($item) {
return explode('-', $item)[1];
})
Steps to follow:
define blank array $new_array (to fill single value from foreach loop).
get single value using foreach loop.
use strstr for remove everything before dash and remove '-' using str_replace.
fill single value in $new_array.
return $new_array outside foreach loop.
Below is the code -
$array = ['hr-34', 've-53', 'dv-65'];
$new_array = array();
foreach($array as $key=>$result){
$data = str_replace('-', '', strstr($result, '-'));
$new_array[]= $data;
}
print_r($new_array);
That's all!
https://www.php.net/manual/en/function.array-map.php
https://www.php.net/manual/en/function.explode.php
$array = array_map(function ($item) {
return explode('-', $item)[1];
}, $array)
Edit:
As you changed title from array to collection you can use:
https://laravel.com/docs/9.x/collections#method-map
$collection->map(...)
in a similar way to array_map(...)
$array = ['hr-34', 've-53', 'dv-65'];
$array = collect($array)
->map(fn($item) => explode('-', $item)[1])
->all();
/**
* array:3 [
* 0 => "34"
* 1 => "53"
* 2 => "65"
* ]
*/
dd($array);
Here this code in sandbox
you can use regex with preg_replace as :
$new = array_map(function ($item) {
return preg_replace('/^([^-])+-/', '', $item);
}, $array);
result :
array:3 [
0 => "34"
1 => "53"
2 => "65"
]

Get array object data from exploded array fields in foreach loop

I'm trying to extract data from our JSON data based on given output fields, but I'm not getting a good result.
e.g.
Given fields that I want:
Array
(
[0] => id
[1] => name
[2] => email
[3] => optin_email
)
Those fields exist in my datastring, I want to export those to a CSV.
I can do this, hardcoded
foreach ($jsonString as $value) {
$row = [
$value->id,
$value->name,
$value->email,
$value->phone
];
print_r($row);
}
The above will give me the list/file I need. BUT, I want to make that dynamic based on the data in the array, so, fo rexample, when this is the Array:
Array
(
[0] => id
[1] => name
)
This should be my output:
foreach ($jsonString as $value) {
$row = [
$value->id,
$value->name
];
print_r($row);
}
So I need to dynamicly create the
$value->{var}
I have been trying forever, but I am not seeing it straight anymore.
Tried this:
$rowFields = '';
foreach ($export_datafields AS $v) {
$rowFields .= '$value->' . $v . ',';
}
$trimmed_row_fields = rtrim($rowFields, ',');
foreach ($jsonString as $value) {
$row = $trimmed_row_fields;
print_r($row);
}
And several variations of that:
foreach ($jsonString as $value) {
$row = [$trimmed_row_fields];
print_r($row);
}
Question is: how can I get
$value->VAR
as a valid array key when I only know the VAR name and need the prefixed $value-> object.
I ended up using the following code which works for me. If anybody still has the answer to my original question, please shoot. Always good to know it all.
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$csvFileName");
header("Pragma: no-cache");
header("Expires: 0");
$new_row = implode(",", $export_datafields) . "\n";
foreach ($jsonString as $value) {
foreach ($export_datafields AS $v) {
$new_row .= $value->$v . ',';
}
$new_row = substr($new_row, 0, -1);
$new_row .= "\n";
}
echo $new_row;

Array to String Conversion in JSON

This is my sample JSON data that I need to implode. During that time I'm getting an array to string conversion error.
JSON
{
"user_id" :"110" ,
"parent_id": "115",
"relation_name" : "justin",
"data" :[
{"relation_ship": "brohter"},
{"relation_ship": "sister"}
],
"sum_assured": "89745$-$48721",
"annual_primium":"00000$-$0006557",
"paid_status" : "0$-$1",
"ins_company_name" : "yes",
"renew_date": "2018-10-11$-$2018-10-23"
}
Here is my function for imploding, please help me fix this.
<?php
if (isset($data)) {
foreach ($data as $value) {
$data_insert['user_id'] = $user_id;
$data_insert['parent_id'] = $user_id;
$data_insert['relation_name'] = $data['relation_name'];
$data_insert['relation_ship'] = implode("$-$", $data['data']);
$data_insert['sum_assured'] = implode("$-$", $data['sum_assured']);
$data_insert['annual_primium'] = implode("$-$", $data['annual_primium']);
$data_insert['paid_status'] = implode("$-$", $data['paid_status']);
$data_insert['renew_date'] = implode("$-$", $data['renew_date']);
$data_insert['ins_company_name'] = implode("$-$", $data['ins_company_name']);
DB::table('health_tbl')->insert($data_insert);
}
return response()->json(['status' => 'Success', 'message' => 'Success']);
}
return response()->json(['status' => 'Failure', 'message' => 'Failed']);
You can't implode something that isn't an array. Implode is basically used to turn something like this:
array('something', 'something else')
Into something like this:
implode('<delim>', array('something', 'something else')) => "something<delim>something else"
Are you intending on exploding them to tear them into their own arrays?
In that case, use explode like this:
explode('$-$', $data['paid_status']);
That would return (using your data above):
array("0", "1")

How to combine two different tables into one in codeigniter?

In this code, I have two different tables i.e. skill_master and jobs_category. Now, I want to get these two different table data into one and also convert its data into JSON format using json_encode.
$this->db->select('category');
$this->db->from('jobs_category');
$this->db->order_by('category');
$query1 = $this->db->get();
$result1 = $query1->result_array();
$this->db->select('key_skills');
$this->db->from('skill_master');
$this->db->order_by('key_skills');
$query2 = $this->db->get();
$result2 =$query2->result_array();
$arr = array();
foreach($result1 as $row)
{
foreach($result2 as $rows)
{
$arr[] = $row['category'].','.$rows['skill_master'];
}
}
$json = json_encode($arr);
echo $json;
For example:
table1: skill_master
key_skills
==========
java
php
dot net
table2: jobs_category
category
========
IT Jobs
Air line Jobs
Hardware Jobs
Now, Here I have two tables here. Now, I want to combine these two tables and want data in JSON format like ["java", "PHP", "dot net", "IT Jobs", "Air Line Jobs", "Hardware Jobs"]. So, How can I do this? Please help me.
Thank You
$this->db->select('category');
$this->db->from('jobs_category');
$this->db->order_by('category');
$query_category= $this->db->get();
$result_category = $query_category->result_array();
$this->db->select('key_skills');
$this->db->from('skill_master');
$this->db->order_by('key_skills');
$query_skills = $this->db->get();
$result_skills =$query_skills->result_array();
If You get records from table jobs_category and skill_master like this
$result_category =
[
'0' => ['category' => 'IT Jobs'],
'1' => ['category' => 'Air line Jobs'],
'2' => ['category' => 'Hardware Jobs']
];
$result_skills =
[
'0' => ['skill_master' => 'java'],
'1' => ['skill_master' => 'php'],
'2' => ['skill_master' => 'dot net']
];
$final_arr = $final_category_arr = $final_skill_arr = [];
foreach($result_category as $category_row)
{
$final_category_arr[] = $category_row['category'];
}
foreach($result_skills as $skill_row)
{
$final_skill_arr[] = $skill_row['skill_master'];
}
$final_arr = array_merge($final_category_arr, $final_skill_arr);
$json = json_encode($final_arr);
echo $json;
Result will be like this
["IT Jobs","Air line Jobs","Hardware Jobs","java","php","dot net"]
renaming column while fetching and merging data should work. try following code
$this->db->select('category');
$this->db->from('jobs_category');
$this->db->order_by('category');
$query_category= $this->db->get();
$result_category = $query_category->result_array();
$this->db->select('key_skills as category');
$this->db->from('skill_master');
$this->db->order_by('key_skills');
$query_skills = $this->db->get();
$result_skills =$query_skills->result_array();
$result = array_merge($result_category,$result_skills);

SilverStripe 3.1 loop associative array

In SilverStripe 3.1 I have a function that loops through an array and outputs its contents.
The output it gives me is:
Layout: John
Strategy: John
Management: Martin
In this example John has more than one job.
I would like to group the jobs if a person has more than one job.
This is my desired Output:
Layout and Strategy: John
Management: Martin
//$InfoFieldArray = array('Layout' => 'John', 'Strategy' => 'John', 'Management' => 'Martin');
public function createInfoFields($InfoFieldArray){
$Info = ArrayList::create();
foreach($InfoFieldArray as $key => $value ){
$fields = new ArrayData(array('FieldName' => $key, 'Value' => $value));
$Info->push($fields);
}
return $Info;
}
How do I alter my function to achieve my desired output?
One possible solution to that is by restructuring the data before adding it to the ArrayList.
public function createInfoFields($InfoFieldArray)
{
$info = array();
foreach ($InfoFieldArray as $job => $person)
{
if (!isset($info[$person]))
{
$info[$person] = array();
}
$info[$person][] = $job;
}
$result = ArrayList::create();
foreach ($info as $person => $jobs)
{
$fields = new ArrayData(array('FieldName' => implode(' and ', $jobs), 'Value' => $person));
$result->push($fields);
}
return $result;
}
What I have done is go over the array of jobs and the person assigned and flipped it the other way around, so I have an array of people with a list of jobs. This allows me to then just call implode in PHP, joining the various jobs by the word and.
There are some potential drawbacks, if there are two people named "John", they will be treated as one as I am using the name as the array key.
Also, if there are three jobs for a person, it will list it like "Layout and Strategy and Management". To avoid that, we need to modify the second foreach loop in my code to something like this:
foreach ($info as $person => $jobs)
{
$jobString = null;
if (count($jobs) > 1)
{
$jobString = implode(', ', array_slice($jobs, 0, -1)) . ' and ' . array_pop($jobs);
}
else
{
$jobString = $jobs[0];
}
$fields = new ArrayData(array('FieldName' => $jobString, 'Value' => $person));
$result->push($fields);
}
When there is more than 1 job for a person, we want to implode (glue together) the array pieces for the $jobs array however we don't want the last element at this point. Once array is glued together, we append with with and along with the last item.

Resources