reading multidimensional arrays using for each in php - php

I have an array in the following format:
0 =>
array (size=4)
'timestamp' => string '1/2/2014 7:59' (length=13)
'phase1' => string '16264' (length=5)
'phase2' => string '16671' (length=5)
'phase3' => string '7146' (length=4)
1 =>
array (size=4)
'timestamp' => string '2/2/2014 7:59' (length=13)
'phase1' => string '16310' (length=5)
'phase2' => string '16105' (length=5)
'phase3' => string '7211' (length=4)
I want to create another array within another item to the array that will add the values of phase1, phase2 and phase3
Something like this.
$total_value[$i]['total'] = $csv_file[$i]['phase1'] + $csv_file[$i]['phase2'] + $csv_file[$i]['phase3'];
I tried using a for loop but it doesn't work:
for($i = 0; i < $size_of_array; $i++ ) {
$total_value[$i]['total'] = $csv_file[$i]['phase1'] + $csv_file[$i]['phase2'] + $csv_file[$i]['phase3'];
}

Try:
foreach($csv_file as $key => $values) {
$total_value[$key]['total'] = $values['phase1'] + $values['phase2'];
//$total_value[$key] = $values['phase1'] + $values['phase2'];
}
I would use the commented line so I just had a single-dimension (easier to work with):

Please see how you can deal with objects using foreach
try using foreach by referring
http://www.php.net/manual/en/language.oop5.iterations.php

Related

PHP: Remove empty values from array and shift values up

I'm trying to create a function that shifts array values up a key if the previous key is empty and one after is set. E.g. this array:
array (size=4)
'row1' => string 'row1' (length=4)
'row2' => string '' (length=0)
'row3' => string '' (length=0)
'row4' => string 'row4' (length=4)
should become this after my function call:
array (size=4)
'row1' => string 'row1' (length=4)
'row2' => string 'row4' (length=4)
'row3' => string '' (length=0)
'row4' => string '' (length=0)
I do have a working function, however, it uses a lot of if statements and I'm 100% sure that it could be done more efficiently, any ideas on how to achieve efficiently?
Thanks
You can do this in a single line, making use of array_ functions.
$o = array_combine(array_keys($input), array_pad(array_filter($input), count($input), ''));
array_filter will, by default, remove any empty values from the array
array_pad will pad the array to the length of the original array, adding an empty string
array_keys will get the keys of the original array
array_combine will combine the keys with the values
The above would output the following:
array (size=4)
'row1' => string 'row1' (length=4)
'row2' => string 'row4' (length=4)
'row3' => string '' (length=0)
'row4' => string '' (length=0)
Here's a demo
Lets try this with a big array, and hope this will help you out. The way of question is different but your question is same as
1. Getting empty values at end.
2. Non empty at starting without changing order
3. Without changing keys order
If you think about any array this result come to end.
Try this code snippet here
<?php
$array=$tempArray=array(
'row1' => 'row1',
'row2' => '' ,
'row3' => '',
'row6' => 'row6' ,
'row4' => 'row4' ,
'row5' => '',
'row7' => 'row7' ,
'row8' => ''
);
$result=array();
$tempArray= array_values($tempArray);
$tempArray=array_values(array_filter($tempArray));
foreach(array_keys($array) as $key_key => $key)
{
if(!empty($tempArray[$key_key]))
{
$result[$key]=$tempArray[$key_key];
}
else
{
$result[$key]="";
}
}
print_r($result);
Output:
Array
(
[row1] => row1
[row2] => row6
[row3] => row4
[row6] => row7
[row4] =>
[row5] =>
[row7] =>
[row8] =>
)
unfortunately you did not share your code, so we cannot know what you do exactly
also it would be helpful if you added the array as code we can run directly and do not need to edit/re-create
I would
ignore the keys for processing the list when possible
unset entries that are nor needed any longer
iterate lists with foreach
apart from this you can sort lists in PHP (by value, key; asc, desc; with/without association), they have a nice overview on that in the manual.
example steps:
<?php
$a['row1'] = 'row1';
$a['row2'] = '';
$a['row3'] = '';
$a['row4'] = 'row4';
print_r( $a );
arsort($a);
print_r( $a );
//get rid of double entries
$f=array_flip( $a );
//get rid of empty entries
unset($f['']);
print_r( array_flip( $f ) );
?>
EDIT
$yourarr=array('row1'=>"row1",'row2'=>"",'row3'=>"",'row4'=>"row4");
$array1=array();
$array2=array();
foreach ($yourarr as $key =>$val){
if(empty($val)){
$array2[$key]=$val;
}else{
$array1[$key]=$val;
}
}
$newarr=array_merge($array1,$array2);
//<!-- Try This if you want to remove the empty indexes just put ! infront of the empty and delete the else part and to reset the row count -->
$i=1;
$newarr2=array();
foreach($newarr as $key =>$val){
$newarr2['row'.$i]=$val;
$i++;
}
var_dump($newarr2);
OUTUT
D:\wamp64\www\test\index.php:21:
array (size=4)
'row1' => string 'row1' (length=4)
'row2' => string 'row4' (length=4)
'row3' => string '' (length=0)
'row4' => string '' (length=0)

SQL/PHP sort fields from a form to make insert

I've got a form which users can add new rows by clicking on a button and automatically, it adds +1 on the field's name.
So for example, I've got my train_id_1, train_type_1 and my user wants to add a new one, so now I've got train_id_2 and train_type_2.
In order to save this in my database, I would like to sort and seperate train_type_1 / train_type_2... to make a foreach and then to save in my database.
So, the var_dump of my $_POST looks like :
array (size=60)
'train_id_1' => string ' 07:36' (length=6)
'train_type_1' => string ' -Z' (length=3)
'user_id_1' => string 'CPN' (length=3)
'event_criter_1' =>
array (size=3)
0 => string 'test' (length=4)
1 => string '234' (length=3)
2 => string '532' (length=3)
'train_id_2' => string ' 08:32' (length=6)
'train_type_2' => string ' -X' (length=3)
'user_id_2' => string 'CPN' (length=3)
'event_criter_2' =>
array (size=3)
0 => string 'TESTG' (length=5)
1 => string 'GGG' (length=3)
2 => string 'AETG' (length=4)
'train_id_3' => string ' 08:36' (length=6)
'train_type_3' => string ' -Z' (length=3)
'user_id_3' => string 'CPN' (length=3)
'event_criter_3' =>
array (size=1)
0 => string '' (length=0)
'train_id_4' => string ' 09:04' (length=6)
'train_type_4' => string ' -X' (length=3)
'user_id_4' => string 'CPN' (length=3)
'event_criter_4' =>
array (size=1)
0 => string '' (length=0)
Do you know how I can make abcd_1 separate from abcd_2 to make my foreach (or another solution) ?
Thank you!
Loop through your array, matching _1 and insert the posted elements as one row. Then increment and match _2 etc..
$postedElements = $_POST;
$elementsPerRow = 4;
$numRows = count($postedElements)/$elementsPerRow;
// loop through the number of 'rows' to insert
for($i=1;$i<=$numRows;$i++){
// Build an array to store matched elements to insert
$elementsToInsert = array();
//process the complete _POST array each time...
foreach($postedElements as $name => $value){
// ...get the 'row' (the bit after the underscore)...
//list($value,$row) = explode('_',$name); // doesn't work for 2 underscores..
$row = end(explode($name)); // This will
if($row == $i){
// ...and add elements that match to an insert array
// $elementsToInsert[] = $name;
$elementsToInsert[$name] = $value;
}
}
// insert $elementsToInsert into DB
}
I think, at first You need to have a amount of records in array through count($arr). Then use usual for loop:
//output of field names
for ($i = 0; $i < count($arr); $i++){
//Work with array
}
Make a new array.
Then add a data from loop into new array.
I think it could help You.
And by which reason You need to sort them?

make serialized form POST to php

my problem is that I'm sending html form data via jquery here's the code :
$('#search_button').click(function(event) {
var track_load = 0; //total loaded record group(s)
var loading = false; //to prevents multipal ajax loads
var total_groups = <?php echo $total_groups; ?>; //total record group(s)
var Data = $("#srch_form").serializeArray();
console.log(Data);
$('#results').load("autoload_process.php", {
data:Data,
'group_no':track_load},
function() {track_load++;}); //load first group
});
and in the php receiving page I'm getting an array with one array per name&value pair inside like this :
array (size=4)
0 =>
array (size=2)
'name' => string 'srch_word' (length=9)
'value' => string '' (length=0)
1 =>
array (size=2)
'name' => string 'srch_cat-2' (length=10)
'value' => string '2' (length=1)
2 =>
array (size=2)
'name' => string 'srch_cat-5' (length=10)
'value' => string '5' (length=1)
3 =>
array (size=2)
'name' => string 'srch_cat-6' (length=10)
'value' => string '6' (length=1)
But before with html only form post I was getting one array with the pairs inside :
array (size=4)
'srch_word' => string '' (length=0)
'srch_cat-2' => string '2' (length=1)
'srch_cat-5' => string '5' (length=1)
'srch_cat-6' => string '6' (length=1)
And I use to access the values like an associative array would do ($_POST['srch_word'], or even just $srch_word would work ), now I can't do that.
¿How can I get one array from the jquery post or how can I reduce this array of arrays to one array in the php file or what should I do in this case?
I would appreciate your help.
this is sample maybe usefull for you as long number of child array always two
<?php
$keys = array();
$value = array();
$serialize = array(array('name' => 'srch_word', 'value' => ''), array('name' => 'srch_cat-2', 'value' => '2'));
foreach ($serialize as $key) {
array_push($keys, $key['name']);
array_push($value, $key['value']);
}
$final = array_combine($keys, $value);
echo '<pre>',print_r($final),'</pre>';
?>
replace $serialize as your array define
please vote if you like it

converting array to stdClass in CodeIgniter

I am returning data from two tables in CodeIgniter with the function below
public function test()
{
$this->db->select('*');
$this->db->from('WHOUSE1.DLY_BWR_DLY_PERFORMANCE');
$this->db->join('WHOUSE1.DATE_DIM', 'WHOUSE1.DATE_DIM.DATE_KEY = WHOUSE1.DLY_BWR_DLY_PERFORMANCE.BDP_DATE');
$query = $this->db->get();
return $query->result_array();
}
Using var_dump I am getting the result below
array (size=3226)
0 =>
array (size=121)
'BDP_ID' => string '945149' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040807' (length=8)
'BDP_DAY_CODE' => string '6' (length=1)
'BDP_TAKE' => string '4923.78' (length=7)
'BDP_PAYOUT' => string '3779.22' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '636' (length=3)
1 =>
array (size=121)
'BDP_ID' => string '945150' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040809' (length=8)
'BDP_DAY_CODE' => string '1' (length=1)
'BDP_TAKE' => string '2848.3' (length=6)
'BDP_PAYOUT' => string '4190.34' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '280' (length=3)
But what I will like to get is this
array (size=3226)
0 =>
object(stdClass)[27]
'BDP_ID' => string '945149' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040807' (length=8)
'BDP_DAY_CODE' => string '6' (length=1)
'BDP_TAKE' => string '4923.78' (length=7)
'BDP_PAYOUT' => string '3779.22' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '636' (length=3)
1 =>
object(stdClass)[29]
'BDP_ID' => string '945150' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040809' (length=8)
'BDP_DAY_CODE' => string '1' (length=1)
'BDP_TAKE' => string '2848.3' (length=6)
'BDP_PAYOUT' => string '4190.34' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '280' (length=3)
I can't seem to get a way of converting the array into object(stdClass) Any help will be appreciated as am new to CodeIgniter.
Array to stdClass can be done in php this way.
stdClass:: __set_state(array());
Or a nicer way.
$a = (object) array();
Use this code in Your Model ( change your table name and select, distinct fileds )
$this->db->select('DISTINCT(subcategory)');
$this->db->from('tbl_property');
$this->db->where('status','1');
$data = $this->db->get()->result();
$sub_id = array();
foreach ($data as $row)
{
array_push($sub_id,$row->subcategory);
}
$this->db->from('tbl_subcategory');
$this->db->where_in('id',$sub_id);
$data1 = $this->db->get()->result();
return $data1;
use
return $query->result();
This function returns the query result as an array of objects, or an empty array on failure. Typically you'll use this in a foreach loop, like this:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
Edit:
If you just want to print you can use var_dump() or print_r().
var_dump($obj);
print_r($obj);
If you want an array of all properties and their values use get_object_vars().
$properties = get_object_vars($obj);
print_r($properties);
According to the same documentation for Codeigniter I detail:
result_array()
This function returns the query result as a pure array, or an empty array when no
result `is produced. Typically you'll use this in a foreach loop, like this:`
and ..
result()
This function returns the query result as an array of objects, or an empty array
on failure.
You should return your data in this way
return $query->result();

multiarray - how to keep first 3 index groups of each source type

I have a multi-array where I need to keep the first 3 index groups and remove the rest from the multiarray (in each group).
See multiarray here: https://gist.github.com/no1uknow/6887497
So:
In this example I need the multi-array to keep: The first 3 Heavy, Lite, Intermediate, etc (these are identified by the source_type_cd)
Example of the Lite part of the array after the first 3 are kept:
0 =>
array (size=9)
'validated_ata' => string '25' (length=2)
'source_type_cd' => string 'Lite' (length=4)
'validated_subata' => string '22' (length=2)
'action_cd' => string '3' (length=1)
'object_cd' => string '5' (length=1)
'malfunction_cd' => string '29' (length=2)
'corrective_action_txt' => string 'Repair-Passenger Seat-Loose / Displaced' (length=39)
'rec_count' => string '00050' (length=5)
'group_id' => int 48
1 =>
array (size=9)
'validated_ata' => string '25' (length=2)
'source_type_cd' => string 'Lite' (length=4)
'validated_subata' => string '22' (length=2)
'action_cd' => string '3' (length=1)
'object_cd' => string '5' (length=1)
'malfunction_cd' => string '1' (length=1)
'corrective_action_txt' => string 'Repair-Passenger Seat-Inoperative' (length=33)
'rec_count' => string '00047' (length=5)
'group_id' => int 44
2 =>
array (size=9)
'validated_ata' => string '25' (length=2)
'source_type_cd' => string 'Lite' (length=4)
'validated_subata' => string '22' (length=2)
'action_cd' => string '3' (length=1)
'object_cd' => string '5' (length=1)
'malfunction_cd' => string '31' (length=2)
'corrective_action_txt' => string 'Repair-Passenger Seat-Worn / Chaffed / Frayed' (length=45)
'rec_count' => string '00042' (length=5)
'group_id' => int 50
You will simply have to loop through the array and look if it has any of those values and place into a new array.
Example (where $arr is your multiarray):
// My silly solution for knowing what to look for
// When one is found, it will be removed from the array.
$find = array('Lite','Lite','Lite','Intermediate','Intermediate','Intermediate','Heavy','Heavy','Heavy');
// New array where your the values you want will be placed in
$new_arr = array();
foreach($arr as $v) {
// No need to keep looking if there's no more to find.
if(empty($find))
break;
// Look in $find array if current "source_type_cd" is still sought-after
$key = array_search($v['source_type_cd'], $find);
if($key !== false) {
$new_arr[] = $v; // Add to new array
unset($find[$key]); // Remove from "find" array
}
}
Thanks Colandus I actually figured it out like this... I was trying to avoid to many loops.
In a loop above this I set the source_type_cd in an array:
$groups[]=$value['source_type_cd']
Next I loop through the array and take the top 3 of each group by using array_splice twice and then merging back into a new array.
(also, I'm using a start and end point ($group_count).)
$start = 0;
$group_count = $i+1;
$top_count = 3;
foreach($groups as $k => $v) {
$top_count_array = array_merge((array)$top_count_array, (array)array_slice(array_slice($sorted_array, $start, $group_count, true),0,$top_count,true));
$start = $start+$group_count;
}
var_dump($top_count_array);
Again appreciate the input. Tried to shorten this code down from so many loops. Also requirements will change for grabbing the amount of $top_count and $group_count... Needed something a little more dynamic. :-)

Categories