I got 2 arrays:
$ping_array = array();
$ping_array[] = '400';
$ping_array[] = '200';
$ping_array[] = '600';
$ping_array[] = '100';
$timestamp_array = array();
$timestamp_array[] = '2013-03-25 16:30:07';
$timestamp_array[] = '2013-03-25 16:30:39';
$timestamp_array[] = '2013-03-25 18:30:06';
$timestamp_array[] = '2013-03-25 18:45:49';
I want to make something like this (i dont know how its called):
$combined_array = array(
'time' => $timestamp_array,
'ping' => $ping_array
);
so later on i could use the 2 arrays combined like this:
foreach ($combined_array as $ca=> $values) {
echo $values['ping'];
echo $values['time'];
}
Thx guys this combine_array is amazing
Try this:
$combined_array = array();
foreach ($ping_array as $key => $value){
$combined_array[] = array(
'time' => $timestamp_array[$key],
'ping' => $value
);
}
What about this?
for ($i=0; $i<count($timestamp_array); $i++) {
$combined_array[$i]["ping"] = $ping_array[$i];
$combined_array[$i]["time"] = $timestamp_array[$i];
}
PHPs array_combine: "Creates an array by using one array for keys and another for its values"
$combined_array = array_combine($timestamp_array, $ping_array);
Then just repeat through similar to what you included:
foreach($combined_array as $time => $ping) {
echo $ping;
echo $time;
}
How about php 'array_merge_recursive'? It does exactly what you are looking for. It is found on php 4 and up.
What you could do is make array of objects, like this:
class PingInfo {
public $ping;
public $time;
public function PingInfo($ping, $time) {
$this->ping = $ping;
$this->time = $time;
}
}
$pingInfos = array();
$pingInfos[] = new PingInfo('400', '2013-03-25 16:30:07');
$pingInfos[] = new PingInfo('300', '2013-03-25 16:50:13');
You could build it from two array like this:
$pingInfos = array();
for ($i = 0; $i < count($ping_array); $i++)
$pingInfos[] = new PingInfo($ping_array[$i], $timestamp_array[$i]);
Now you can access it like this:
foreach ($pingInfos as $pingInfo) {
echo $pingInfo->ping;
echo $pingInfo->time;
}
Related
I have three table for student first one is roll_no
second is center details
third is rooms details
$anil = array();
$exam_no_students = array();
$session_usr['user']= $this->session->userdata('user_name');
$total_students['total_stu']=$this->DBfunction->totalCountAll('roll_no');
$exam_centers['no_of_centers']= $this->DBfunction->count_centers();
$exam_centers1= $this->DBfunction->count_centers();
foreach ($exam_centers1 as $center_code => $center_details){
$center_code = array('center_id' =>$center_details->center_id);
$center_table='exam_center';
$center_full_details =$this->DBfunction->getArrayWhereResult($center_table,$center_code);
foreach ($center_full_details as $full => $full_de) {
$fullstudent = array('center_f_id' =>$full_de->center_id,
'center_f_name' =>$full_de->exam_center,
'center_f_addres' =>$full_de->exam_center_address ,
'center_f_city' =>$full_de->village ,
'center_f_count' =>$center_details->count);
}
array_push($exam_no_students, $fullstudent);
$center_f_details =$this->DBfunction->getArrayWhereResult($center_table,$center_code);
foreach ($center_f_details as $roomss => $rooms) {
$room_id = array('exam_center_id' =>$rooms->id);
$center_rooms =$this->DBfunction->getArrayWhereResult('exam_center_rooms',$room_id);
foreach ($center_rooms as $rooms_c => $roomsdetails) {
$center_with_rooms['anil'] = array('center_id'=>$rooms->center_id,
'center_name'=>$rooms->exam_center,
'center_main'=>$roomsdetails->exam_center_id,
'no_of_students'=>$center_details->count,
'room_no'=>$roomsdetails->room_no,
'no_of_seating'=>$roomsdetails->noofseating, 'noofrow'=>$roomsdetails->noofrow,
'noofcol'=>$roomsdetails->noofcol
);
}
}
I want to assign student into rooms for exam like below table
i am so confused to do this.
I got solution for above mentioned query using array_slice(). and get desired result.
public function Student_shift(){
$stateus='Approved';
$statuss = array('status' =>$stateus);
$table ='exam_center';
$get_centers=$this->DBfunction->getArrayWhereResult($table,$statuss);
$new_array = array();
foreach ($get_centers as $centers => $centers_name){
$i=1;
$centerid=$centers_name->center_id;
$main_id = $centers_name->id;
$center_where = array('center_id' =>$centerid);
$roll_table='roll_no';
$all_center_student = $this->DBfunction->getArrayWhereResult($roll_table,$center_where);
$all_center_student_count=count($all_center_student);//die;
$rooms_where = array('exam_center_id' =>$main_id);
$room_table= 'exam_center_rooms';
$rooms_details= $this->DBfunction->getArrayWhereResult($room_table, $rooms_where);
$cout = count($all_center_student);
$diff_diff=$all_center_student;
$start =0;
$shift=1;
$rooms_seating = 0;
while ($diff_diff){
$start =0;
$rooms_seating = 0;
$i=0;
ini_set('max_execution_time', 0);
ini_set('memory_limit','2048M');
foreach ($rooms_details as $roo => $rooms_ava){
$sliced_array = array_slice($diff_diff, $start, $rooms_ava->noofseating-2);
$start = $rooms_ava->noofseating-2;
foreach ($sliced_array as $key1 => $all) {
$students_with_rooms = array('enrollment' =>$all->enrollment,
'center_id' =>$all->center_id,
'roll_no' =>$all->roll_no,
'stu_class' =>$all->stu_class,
'room_no' =>$rooms_ava->room_no,
'shift_id'=>$shift
);
$roll_where = array('roll_no' => $all->roll_no);
$table='roll_no';
$data = array('room_no' => $rooms_ava->room_no,
'shift_id'=>$shift
);
$this->DBfunction->updateArrayWhereResult($table, $roll_where, $data);
array_push($new_array, $students_with_rooms);
}
$rooms_seating = $rooms_seating+$rooms_ava->noofseating-2;
$i++;
}
$diff_diff = array_slice($diff_diff, $rooms_seating);
$shift++;
}
}
redirect('Admin/abcd');
}
How would you transform a monodimensional array into a multidimensional array in PHP? Suppose you have something like this
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
And you want a function to transform it into
$array['breakfast'] = 'milk';
$array['meal']['firstdish'] = 'pasta';
$array['meal']['seconddish']['maincourse'] = 'veal';
$array['meal']['seconddish']['dressing'] = 'fries';
$array['meal']['dessert'] = 'pie';
The same function should of course transform
$tire['ean'] = '3286347717116';
$tire['brand.maker'] = 'BRIDGESTONE';
$tire['brand.model.name'] = 'POTENZA';
$tire['brand.model.variant'] = 'RE 040 RFT * SZ';
into
$tire['ean'] = '3286347717116';
$tire['brand']['maker'] = 'BRIDGESTONE';
$tire['brand']['model']['name'] = 'POTENZA';
$tire['brand']['model']['variant'] = 'RE 040 RFT * SZ';
I was thinking of using explode, then eval on the results, but eval always feels like cheating to me and I guess it would keep my code from running in HipHop.
The reason I want to do this is that I have to export lots of different tables from a database into XML files, and I already have a robust function that turns a multidimensional array into XML.
Like this:
function build(array &$trg, array $k,$key,$value) {
$p = &$trg;
while ( !empty($k) ) {
$nk = array_shift($k);
if ( !isset($p[$nk]) ) {
$p[$nk] = [];
}
$p = &$p[$nk];
}
$p[$key] = $value;
return $p;
}
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
$out = [];
foreach ($array as $key => $value ) {
$path = explode('.',$key);
$last = array_pop($path);
build($out,$path,$last,$value);
}
print_r($out);
You were on the right track with explode, but there's no need to use eval. Once you've got the pieces of the keys available, you can loop over them and incrementally assign a pointer into a new array:
<?php
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
$result = [];
$target = null;
foreach ($array as $key => $value) {
// Start by targeting the base of our resulting array
$target =& $result;
// Break the keys apart into pieces
$keyParts = explode('.', $key);
// Assign new target based on indexing into the result array one "piece" at a time
while ($part = array_shift($keyParts)) {
$target =& $target[$part];
}
// Finally, assign the value to our target
$target = $value;
}
See https://eval.in/625627
I have a site developed in php (codeigniter) and I want to merge some array with same structure.
This is the constructor of my array:
$first = array();
$first['hotel'] = array();
$first['room'] = array();
$first['amenities'] = array();
/*
Insert data into $first array
*/
$second = array();
$second['hotel'] = array();
$second['room'] = array();
$second['amenities'] = array();
/*
Insert data into $second array
*/
After insert data I want to merge this array but the problem is that I have subarray inside it and I want to create a unique array like that:
$total = array();
$total['hotel'] = array();
$total['room'] = array();
$total['amenities'] = array();
This is the try to merge:
$total = array_merge((array)$first, (array)$second);
In this array I have only the $second array why?
Use the recursive version of array_merge called array_merge_recursive.
It seems like array_merge doesn't do what you think it does: "If the input arrays have the same string keys, then the later value for that key will overwrite the previous one." Try this:
function merge_subarrays ($first, $second)
$result = array();
foreach (array_keys($first) as $key) {
$result[$key] = array_merge($first[$key], $second[$key]);
};
return $result;
};
Then call it as:
$total = merge_subarrays($first, $second);
and, if I've correctly understood your question, $total will contain the result you're looking for.
There is no standard way of doing it, you just have to do something like:
<?php
$first = array();
$first['hotel'] = array('hello');
$first['room'] = array();
$first['amenities'] = array();
/*
Insert data into $first array
*/
$second = array();
$second['hotel'] = array('world');
$second['room'] = array();
$second['amenities'] = array();
$merged = array();
foreach( $first as $key => $value )
{
$merged[$key] = array_merge( $value, $second[$key] );
}
print_r( $merged );
I'm quite lost, in the following code:
while($row = mysqli_fetch_object($result)){
$similar_games[$row->game_id]['id'][] = $row->id;
$similar_games[$row->game_id]['name'][] = $row->name;
$similar_games[$row->game_id][$type] = 0;
}
foreach($similar_games as $originalGameKey => $originalGame){
//Can be a case where union gets unset, and not populated. scares ksort();
$union = array();
$similar_values = array();
$union = $similar_concepts;
foreach($originalGame['id'] as $similarGameKey => $similarGame){
if(!isset($union[$similarGame])){
$union[] = $similarGame;
}
}
foreach($originalGame['id'] as $similarGameKey => $similarGame){
if(isset($union[$similarGame])){
$similar_values[] = $similarGame;
}
}
$similar_games[$originalGameKey]["union"] = $similar_values;
}
At the line $similar_values[] = $similarGame; I'm attempting to get the $row->name rather than the $row->id
But I don't know how to make the foreach which is based on the ['id'] access the ['name'] values.
If this is too confusing, I can try to clarify, but I'm having trouble here myself.
I just changed:
foreach($originalGame['id'] as $similarGameKey => $similarGame){
if(isset($union[$similarGame])){
$similar_values[] = $similarGame;
}
}
$similar_games[$originalGameKey]["union"] = $similar_values;
To:
for($i = 0; $i<count($originalGame['id']);$i++){
if(isset($union[$originalGame['id'][$i]])){
$similar_values[] = $originalGame['name'][$i];
}
}
$similar_games[$originalGameKey]["union"] = $similar_values;
I have an array that I declare like this:
$health_array = array( );
For every iteration I try to put these 3 items in it like this:
$health_array["num_problems"] = $num_problems;
$health_array["category_id"] = $category_id;
$health_array["category_name"] = $category_name;
But when I loop through the array I get gibberish. Here is how I loop through it:
foreach ($health_array as $i => $row)
{
echo '<p>'.$row['category_name'].' '.$row['category_id'].' '.$row['num_problems'].'</p>';
}
Any idea what I am doing wrong?
Thanks!!
Your problem comes from the fact that you want to do a multi-dimensional array and you're creating a monodimensional one, by overwriting each time the same 3 elements.
You should do something like:
$health_array = array();
$tmp = array();
$tmp["num_problems"] = 5;
$tmp["category_id"] = 8;
$tmp["category_name"] = "something";
$health_array[] = $tmp;
$tmp["num_problems"] = 15;
$tmp["category_id"] = 22;
$tmp["category_name"] = "something else";
$health_array[] = $tmp;
foreach ($health_array as $h)
{
echo $h["num_problems"]." - ".$h["category_id"]." - ".$h["category_name"]."<br />";
}
For every iteration I try to put these 3 items in it like this:
$health_array["num_problems"] = $num_problems;
$health_array["category_id"] = $category_id;
$health_array["category_name"] = $category_name;
It looks like you meant to build your array like this instead:
$health_array[] = array(
"num_problems" => $num_problems,
"category_id" => $category_id,
"category_name" => $category_name
);
This makes an array of arrays, where previously you were overwriting the keys of the same array for each iteration.