How to combine two different tables into one in codeigniter? - arrays

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

Related

How to insert data in Json Format in Codeigniter

I have 3 fields in my database and I want to add data by row-wise, please help me to add this data in the database.
Use this example for insert json data into database table
$data = array(
'name'=>$this->input->post('name'),
'mobile'=>$this->input->post('phone_number'),
'email'=>$this->input->post('email'),
'message'=>$this->input->post('message'),
'contact_for'=>$this->input->post('user_type'),
'ip_address'=>$this->input->ip_address(),
'browser_info'=>$this->agent->browser().' - '.$this->agent->version(),
);
$json = json_encode($data);
$insertField = array('json_field' => $json);
$this->db->insert('tbl_name', $insertField);
if ($this->db->affected_rows() > 0) {
$insert_id = $this->db->insert_id();
return $insert_id;
}
return false;
You can use
$json = json_encode($data);
https://www.php.net/manual/en/function.json-encode.php
$response = array('status' => 'OK');
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;

Group by query of Eloquent in laravel

I need a query which group by hour then return data.i have a column in database with name time and the value in time column is like 13:12:43.so how can group by hour.And i need the result with order by hour.I'm trying the given query but this query return sum of all units.But i need sum of units on the base of hour like [{ hour:1,unit:0.2232},{ hour:2,unit:0.3232},..so on]
$response = PowerConsumption::groupBY('time')
->selectRaw('round(sum(unit),4) as yAxis')
->where(['device_id' => 2])
->where('date',Carbon::now()->ToDateString)
->orderBy('time')->get();
from you controller :
$response = PowerConsumption::selectRaw('HOUR(time) as hour')
->where(['device_id' => 2])
->where('date',Carbon::now()->ToDateString)
->orderBy('time')->get()->groupBy('hour');
$results = [];
foreach ($response as $hour => $value) {
$results[] = ['hour'=> $hour, 'unit' => round($value->sum('unit'), 4)]
}
you can just do the results foreach in your view if you are not using ajax

How to save multidimensional array in Laravel

Good afternoon !
I am creating a private chat , and I get the first objective , get the message and users with the following code.
public function getEnviarMensajes($id,$identificador){
$user = User::find($identificador);
$idReceptor = $user->id;
$idEmisor = Auth::user()->id;
$mesageuser = MessageUser::with('user')->with('message')->get();
$name = [];
$content = [];
foreach($mesageuser as $users){
foreach($users->message as $mensajes){
if($users->user->id==$idEmisor){
$name[] = $users->user->name;
echo "<p>";
$content[] = $mensajes->contenido;
echo "<p>";
echo $mensajes->created_at;
echo "<p>";
}
if($users->user->id==$idReceptor){
$name[] = $users->user->name;
echo "<p>";
$content[] = $mensajes->contenido;
echo "<p>";
echo $mensajes->created_at;
echo "<p>";
}
}
}
However , I have a problem , this results i need to "join" , in many ocasions I used an array , but in this case ? How I can save differents rows in Laravel ? , also I need to sort this content for datetime row.
Could anyone helps to me ?
I think you can cut your code at this way:
$mesageuser = MessageUser::with('user')->with('message')->get();
$messages = [];
foreach($mesageuser as $users){
foreach($users->message as $mensajes){
$messages[] = [
'nombre' => $users->user->name,
'contenido' => $mensajes->contenido,
'creado' => $mensajes->created_at,
'emisor' => ($users->user->id==$idEmisor) // true or false
];
}
}
return view('chat', ['messages' => $messages]);
The two if statements are useless because inside of them the code is the same. And I had used an multidimensional array in order to store all the messages with the following structure:
[
[
'nombre' => 'Marta',
'contenido' => 'Hola',
'creado' => '24/03/2015',
'emisor' => false
],
[
'nombre' => 'Salomé',
'contenido' => 'adiós',
'creado' => '24/03/2015',
'emisor' => true
]
]
If you want, for example, order by date, then edit your query:
$mesageuser = MessageUser::with('user')->with(['message' => function($query){
$query->orderBy('created_at', 'desc');
}])->get();

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.

Get comma seperated values from PHP array

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")
?>

Resources