php arrray groups by multiple sets - php

i have data in set of groups
each group contains 3 Values As name , mobile , message.
How to store these multiple values in array and get echo of separate group .??
<?php
$full_name = array( );
$full_name["name"] = "john1";
$full_name["mobile"] = "923456812536";
$full_name["message"] = "message1";
$full_name["name"] = "john2";
$full_name["mobile"] = "565656565656";
$full_name["message"] = "message2";
$full_name["name"] = "john3";
$full_name["mobile"] = "444442222222222";
$full_name["message"] = "message3";
$full_name["name"] = "john4";
$full_name["mobile"] = "2222";
$full_name["message"] = "2222222222";
echo $full_name["name"]."</br>".
$full_name["mobile"]."</br>".
$full_name["message"]."</br></br>"
?>

Do your inserts into the array like:
$full_name[] = array(
"name" => "john1",
"mobile" => "923456812536",
"message" => "message1",
);
etc
to give yourself a multi-dimensional array
then loop using
foreach($full_name as $name) {
echo $name['name'], ' ', $name['mobile'], ' ', $name['message'], PHP_EOL;
}

You could use multi dimensional arrays like this
$full_name["name"][0] = "john1";
$full_name["mobile"][0] = "923456812536";
$full_name["message"][0] = "message1";
$full_name["name"][1] = "john2";
$full_name["mobile"][1] = "565656565656";
$full_name["message"][1] = "message2";
And echo a group like this
echo implode(", ", $full_name["name"]);
However, you need to make sure that ["name"][x] corresponds with ["mobile"][x] as these sub arrays are independent of each other. If you use Mark Baker's answer, you know that [x]["name"] belongs to the same person as [x]["mobile"]

This should work for you: With the [] it's going to insert the data into the next field of the array
<?php
$full_name = array( );
$full_name["name"][] = "john1";
$full_name["mobile"][] = "923456812536";
$full_name["message"][] = "message1";
$full_name["name"][] = "john2";
$full_name["mobile"][] = "565656565656";
$full_name["message"][] = "message2";
$full_name["name"][] = "john3";
$full_name["mobile"][] = "444442222222222";
$full_name["message"][] = "message3";
$full_name["name"][] = "john4";
$full_name["mobile"][] = "2222";
$full_name["message"][] = "2222222222";
print_r($full_name["name"]);
echo "</br>";
print_r($full_name["mobile"]);
echo "</br>";
print_r($full_name["message"]);
?>

Related

Select one item from array

So, I wanna select item per item from this array ["A185","A740","A540"]
Like for example I wanna select
$cie[0] = A185 or A740
with something like $cie[0] = A185
This is my code so far, since I fetch that code from a row in a MySQL table.
while ($row = pg_fetch_array($resul)) {
$cie10 = array($row["cie"]);
}
$cie = ["A185","A740"];
$values = array_count_values($cie);
$top = array_slice($values, 0, 1);
print_r($top);
What I get:
Array ( [["A185","A740","A540"]] => 1 )
It just won't work.
I'm Sure you are looking to display the data that is in the array variable
$var = ["A185","A740","A540"]; // Asume as you stored the values in the array called var
foreach($var as $x){
print_r($x);
echo "<br/>";
}
EDIT: Highlighted the code
If i understand your problem. You are looking for this:-
$Fullarray = ["A185","A740","A540"];
$cie = array_slice($Fullarray,0,2);
foreach ($cie as $name) {
$d[] = '"' . $name . '"';
}
$implodekeys = "[".implode(',',$d)."]";
$newarray[$implodekeys] =1;
echo "<pre>"; print_r($newarray);
Hope it helps!

retrieving array as comma separated values in codeigniter

I am using the below code to get the ids from the pr_users table and store it in pr_notification_table,but unable to store the values separated by comma into pr_notifications table. I want to store $notification_data['show_users'] as 1,2,3,4 etc so that notifications are sent to these ids. Its inserting NULL on executing this , I have attached table images also,
pr_notifications table is as below:
My controller code is:
if($data['rows'][0]['last_status'] == 'Accepted')
{
$ids= '22';
$data['success_message'] = $this->exit_common->send_notification_to_all_roles($ids);
echo "Success";
}
My model code is:
function send_notification_to_all_roles($ids)
{
global $USER;
$post_arr = $this->input->post();
$this->db->select('g.*,id');
$this->db->from('pr_users as g');
$this->db->where('userroleid', $ids);
//$this->db->join($this->myTables['pr_users_details'].' as ud','ud.userid = g.userid');
//$this->db->join('pr_users_details as ud','ud.userid = g.userids');
/* $this->db->join($this->myTables['users_details'].' as ud','ud.userid = g.userid');
$this->db->join('pr_resignation_type as gt','gt.id = g.sr_type');*/
$query=$this->db->get();
$return = $query->result_array();
$arr = explode(',',$return);
foreach($arr as $num)
{
echo $num."<br>";
}
print_r($num);
die;
$manager_id = $this->get_value_by_id('managerid','users',$this->session->userdata('admin_id'));
$user_id='1';
$v_memberid = $manager_id . "," . $user_id;
//$manager_id = $this->get_value_by_id('managerid','users',$this->session->userdata('admin_id'));
$notification_data['ref_table'] = 'pr_resignation_requests';
$notification_data['ref_id'] = '1';
$notification_data['modifier_id'] = $USER->id;
$notification_data['show_users'] = $num;
$notification_data['notification_descr']= "A new Job has been created" ;//$manager_id;
$notification_data['notification_text'] = "A new Job has been created";
$notification_data['added_on'] = date("Y-m-d H:i:s");
$notification_data['url'] = 'exits';
$notification_data['uurl'] = 'exits';
$this->db->insert($this->myTables['notifications'],$notification_data);
return 'Resignation Request submitted successfully';
}
I think you have to get notification_id from pr_users table, and then use the following code for get notification_id comma seprated.Assume than your notification id array is :- $user_notification_ids_info
Now go with this code.
$ids = ''; $notification_ids = '';
for($i=0; $i<count($user_notification_ids_info); $i++)
{
$ids = $user_notification_ids_info[$i]['notification_id'];
$notification_ids.= $ids.", ";
}
$notification_ids = substr(trim($notification_ids), 0, -1);
Now simply echo $notification_ids; it will return your comma seprated notification id.
It will helps you try this one.
You want to store $ids comma separated? then use implode().
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(",",$arr);
I hope this will help.

Get Specific Value From Json array in PHP

I'm Try To Access Some specific Value From Return JSON
Real Value is 79#45#597#10#10#10000#M
$retframe = str_ireplace('#',',', $stframe);
echo json_encode(array( 'Value' => $retframe));
///Output Response Back is
{"Value":"79,45,597,10,10,10000,M"}
I Want to Get Only Value of 79,597,10
If you need the 1st, 3rd and 5th number of $stframe
$stframe = '79#45#597#10#10#10000#M';
list($p1,$p2,$p3,$p4,$p5,$p6,$p7) = explode('#',$stframe);
$retframe = $p1 . ',' . $p3 . ',' . $p5;
echo json_encode(array( 'Value' => $retframe));
if you want to get 79,597,10 values statically than you will do it like this way.
$retframe = str_ireplace('#',',', $stframe);//$retframe = '79,45,597,10,10,10000,M';
$rs = explode(",",$retframe);
$array[] = $rs[0];
$array[] = $rs[2];
$array[] = $rs[3];
$array1= implode(",", $array);
echo json_encode(array( 'Value' => $array1));
and you will get result like this : {"Value":"79,597,10"}

dynamic variables from array

I store the field names within an array, in hopes to dynamically create the variables.
I receive a illegal offset type error for the if and else, these two lines:
$data[$tmp_field] = $tmp_field[$id];
$data[$tmp_field] = 0;
I checked the post data and it is posting with the appropriate data, but I am not sure what the problem is.
$student_id stores all the students ids., for example: $student_id = array(8,9,11,23,30,42,55);
function updateStudentInfo() {
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$tmp_field] = 0;
} else {
$data[$tmp_field] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
}
This is the array format I desire:
Array
(
[internet_student] => 1
[non_matriculated_student] => 1
[h_number] => 0
[felony] => 0
[probation] => 1
[dismissed] => 0
)
Added screenshot to give you a visual of the form the data is being posted from
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$field_name] = 0;
} else {
$data[$field_name] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
I am assuming that all these fields are arrays, as otherwise you wouldn't need any loops.
function updateStudentInfo()
{
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
$student_count = count($student_id);
foreach($student_id as $id)
{
$data = array();
foreach($fields as $field)
{
if(array_key_exists($id, $$field))
$data[$field] = ${$field}[$id];
}
}
}
You are trying to use the student id as an array key for the other fields but the HTML form is just a standard indexed array, not keyed to any student data.

Mysql query generation?

I have several different filters and search functions that I need to generate mysql queries for. I am wondering if there is a class or library I can use.
For example if they input there email with a date I need to add WHERE email='email' AND date`='date' in the middle of the sql query. But if they also enter a city then I need to add that.
I was thinking put everything I need to search by in an array and then imploding it by AND ? Does anyone have any better suggestion?
I use Zend_Db for that sort of thing. Quick example, using Zend_Db_Select:
$select = $db->select()->from("users");
if($email) {
$select->where('email = ?', $email);
}
if($date) {
$select->where('date = ?', $date);
}
// etc
// show query
// will output something like SELECT * from `users` WHERE email = 'email' AND date = 'date'
print_r($select->__toString());
// execute
$results = $db->fetchAll($select);
print_r($results);
I use array solution very often as it is most flexible solution for query conditionals
$a[] = "email = 'email'";
$a[] = "firstname LIKE '%firstname%'";
$a[] = "date BETWEEN 'date_a' AND 'date_d'";
$a[] = "id > 123";
$query = ... " WHERE " implode(' AND ', $a);
I'd go for adding all data that is given into an array like this:
$args = array(
'email' => 'test#test.com',
'date' => '2011-01-05',
'city' => 'MyTown'
);
Then just foreach through it adding the key and value to the search
$SQL = "WHERE ";
foreach($args as $key => $val) {
$SQL .= $key."='".$val."'";
//And add the AND or OR where needed
}
Common approach is to create an array that will contain different query parts and just add elements to them, depending on what you need to filter. For example:
<?php
$sql_parts = array(
'select' => array(),
'from' => array(),
'where' => array()
);
if ($filter_by_name != ''){
$sql_parts['select'][] = 'u.*';
$sql_parts['from'][] = 'users AS u';
$sql_parts['where'][] = "u.name = '".mysql_real_escape_string($filter_by_name)."'";
}
if ($filter_by_surname != ''){
$sql_parts['select'][] = 'u.*';
$sql_parts['from'][] = 'users AS u';
$sql_parts['where'][] = "u.surname = '".mysql_real_escape_string($filter_by_surname)."'";
}
//filter by data from another table
if ($filter_by_city_name != ''){
$sql_parts['select'][] = 'u.*, c.*';
$sql_parts['from'][] = 'cities AS c';
$sql_parts['from'][] = 'users AS u';
$sql_parts['where'][] = "c.cityname = '".mysql_real_escape_string($filter_by_city_name)."'";
$sql_parts['where'][] = "c.id = u.cityid";
}
$sql_parts['select'] = array_unique($sql_parts['select']);
$sql_parts['from'] = array_unique($sql_parts['from']);
$sql_parts['where'] = array_unique($sql_parts['where']);
$sql_query = "SELECT ".implode(", ", $sql_parts['select']).
"FROM ".implode(", ", $sql_parts['from']).
"WHERE ".implode(" AND ", $sql_parts['where']);
?>

Categories