I have array of data , and base of that I would like to create as many objects as the array have:
I'm trying to do it with foreach loop, but cant crack it.
foreach($file->data as $item){
$entity = new MappedEntity($file,$counter++);
}
it's working but for example array length =5 , It's overriding the value 5 times and as result I'm having one object with values from fifth record, and I would like to create 5 objects with corresponding properties.
Im total newbie to PHP , any suggestions?
This is quite a weird way to behave, but before further knowledge, you can create 5 instances of your class like this:
$i = 1;
foreach ($file->data as $item) {
${"entity_" . $i} = new MappedEntity($file, $counter++);
$i++;
}
//now you have class instances in variables $entity_1, $entity_2 etc...
Or you can store instances to array like this ( preferred way to do this ):
$arr = [];
foreach ($file->data as $item) {
$arr[] = new MappedEntity($file, $counter++);
}
// now you have array with 5 class instances and you can access them with $arr[0], $arr[1] etc...
Related
I am looking for a way to create new arrays in a loop. Not the values, but the array variables. So far, it looks like it's impossible or complicated, or maybe I just haven't found the right way to do it.
For example, I have a dynamic amount of values I need to append to arrays. Let's say it will be 200 000 values. I cannot assign all of these values to one array, for memory reasons on server, just skip this part.
I can assign a maximum amount of 50 000 values per one array. This means, I will need to create 4 arrays to fit all the values in different arrays. But next time, I will not know how many values I need to process.
Is there a way to generate a required amount of arrays based on fixed capacity of each array and an amount of values? Or an array must be declared manually and there is no workaround?
What I am trying to achieve is this:
$required_number_of_arrays = ceil(count($data)/50000);
for ($i = 1;$i <= $required_number_of_arrays;$i++) {
$new_array$i = array();
foreach ($data as $val) {
$new_array$i[] = $val;
}
}
// Created arrays: $new_array1, $new_array2, $new_array3
A possible way to do is to extend ArrayObject. You can build in limitation of how many values may be assigned, this means you need to build a class instead of $new_array$i = array();
However it might be better to look into generators, but Scuzzy beat me to that punchline.
The concept of generators is that with each yield, the previous reference is inaccessible unless you loop over it again. It will be in a way, overwritten unlike in arrays, where you can always traverse over previous indexes using $data[4].
This means you need to process the data directly. Storing the yielded data into a new array will negate its effects.
Fetching huge amounts of data is no issue with generators but one should know the concept of them before using them.
Based on your comments, it sounds like you don't need separate array variables. You can reuse the same one. When it gets to the max size, do your processing and reinitialize it:
$max_array_size = 50000;
$n = 1;
$new_array = [];
foreach ($data as $val) {
$new_array[] = $val;
if ($max_array_size == $n++) {
// process $new_array however you need to, then empty it
$new_array = [];
$n = 1;
}
}
if ($new_array) {
// process the remainder if the last bit is less than max size
}
You could create an array and use extract() to get variables from this array:
$required_number_of_arrays = ceil($data/50000);
$new_arrays = array();
for ($i = 1;$i <= $required_number_of_arrays;$i++) {
$new_arrays["new_array$i"] = $data;
}
extract($new_arrays);
print_r($new_array1);
print_r($new_array2);
//...
I think in your case you have to create an array that holds all your generated arrays insight.
so first declare a variable before the loop.
$global_array = [];
insight the loop you can generate the name and fill that array.
$global_array["new_array$i"] = $val;
After the loop you can work with that array. But i think in the end that won't fix your memory limit problem. If fill 5 array with 200k entries it should be the same as filling one array of 200k the amount of data is the same. So it's possible that you run in both ways over the memory limit. If you can't define the limit it could be a problem.
ini_set('memory_limit', '-1');
So you can only prevent that problem in processing your values directly without saving something in an array. For example if you run a db query and process the values directly and save only the result.
You can try something like this:
foreach ($data as $key => $val) {
$new_array$i[] = $val;
unset($data[$key]);
}
Then your value is stored in a new array and you delete the value of the original data array. After 50k you have to create a new one.
Easier way use array_chunk to split your array into parts.
https://secure.php.net/manual/en/function.array-chunk.php
There's non need for multiple variables. If you want to process your data in chunks, so that you don't fill up memory, reuse the same variable. The previous contents of the variable will be garbage collected when you reassign it.
$chunk_size = 50000;
$number_of_chunks = ceil($data_size/$chunk_size);
for ($i = 0; $i < $data_size; $i += $chunk_size) {
$new_array = array();
foreach ($j = $i * $chunk_size; $j < min($j + chunk_size, $data_size); $j++) {
$new_array[] = get_data_item($j);
}
}
$new_array[$i] serves the same purpose as your proposed $new_array$i.
You could do something like this:
$required_number_of_arrays = ceil(count($data)/50000);
for ($i = 1;$i <= $required_number_of_arrays;$i++) {
$array_name = "new_array_$i";
$$array_name = [];
foreach ($data as $val) {
${$array_name}[] = $val;
}
}
i have the following problem. i have a large array structure which i assign values from a sql statement:
$data[$user][$month]['id'] = $data->id;
$data[$user][$month]['company'] = $data->company;
...
...
and around 30 other values.
i need to clone this array ($data) and add a subarray like:
$data[$user][$month][$newsubarray]['id'] = $data->id;
$data[$user][$month][$newsubarray]['company'] = $data->company;
...
...
i need to clone it because the original array is used by many templates to display data.
is there a way to clone the array and add the subarray without assign all the values to the cloned array? this blows up my code and is very newbi, but works.
You can use array_map, check the live demo
if you want to pass parameter to array_map(), use this
array_map(function($v) use($para1, $para2, ...){...}, $array);
Here is the code,
<?php
$array =array('user'=> array('month'=>array('id' =>2, 'company' => 3)));
print_r($array);
print_r(array_map(function($v){
$arr = $v['month'];
$v['month'] = [];
$v['month']['newsubarray'] = $arr;
return $v;}
, $array));
You can iterate through the array with nested foreach loops.
It would look similar to this:
foreach ($data as $user=>$arr2) {
foreach ($arr2 as $month=>$arr3) {
foreach ($arr3 as $key=>$value) {
$data[$user][$month][$newsubarray][$key] = $value;
}
}
}
Your last level of array, you can create object, for holding data with implementing ArrayAccess. Then simply by reference, assign object in desire places. This way, you can hold 1 object and use it multi places, but if you change in one - this change in all.
Then you addictionaly, can implements __clone method to clone object correctly.
I have 3 arrays created in the following way:
$start=2013 ;
$end=2015;
$no_of_bars=$to-$from+1;
$xdata=array();
for($year=$start;$year<=$end;$year++){
${"y".$year}=array();
$i=0;
$query=mysql_query("SELECT tld_master.location,tld_dose.year, AVG(tld_dose.dose)*4 as avgdose from tld_master left join tld_dose on tld_master.tldno=tld_dose.tldno where tld_master.site='F' and tld_dose.year=$year GROUP BY tld_dose.year, tld_dose.tldno");
while($result=mysql_fetch_array($query)){
$xdata[$i]=$result['location'];
${"y".$year}[$i]=$result['avgdose'];
$i++;
}
}
It creates three arrays y2013,y2014,y2015.
I have to pass this array to jpgrpah to plot a groupbar. New Bra objects are created in this way
$j=0;
for($year=$start;$year<=$end;$year++, $j++){
${"plot".$year}=new BarPlot(${"y".$year});
${"plot".$year}->SetFillColor($color_array[$j]);
if($year!=$end){$sep=",";}else{$sep="";}
$plots.="$"."plot".$year.$sep;
}
There are three bar plots plot2013,plot2014,plot2015. All these three are arrays. I want to pass these arrays to jpgraph function given below:
$gbplot = new GroupBarPlot($plots);
but this is not working. But if I am changing it to the one given below, it works
$gbplot = new GroupBarPlot(array($plot2013,$plot2014, $plot2015));
I think that in the second one arrays are passed as arguments where as in first one just array name is passed as string. How can I pass the array created inside the for loop to the jpgraph function?
Not tested, but try the code below.
$j=0;
for($year=$start;$year<=$end;$year++, $j++){
${"plot".$year}=new BarPlot(${"y".$year});
${"plot".$year}->SetFillColor($color_array[$j]);
$plots[] = ${"plot".$year};
}
$gbplot = new GroupBarPlot($plots);
I have multiple rows getting returned from a database query.
I am able to get just a row at a time, but I want to put the rows in an array of objects like this:
$trailheads[] = new StdClass;
Loop
{
$trailheads[] = $trailhead; // Put each object into the array of objects
}
But when I try to loop through each array, I am having trouble extracting the values of each row. What is the right way to loop through the returned object and get the values?
The code that does not work is pretty basic:
$returned_obj->o->trailhead_name
But I am actually hoping be able to loop through each array element.
Maybe try casting to array in your for loop, this is untested and may not work as is but should get you on the right track:
foreach ($trailheads as (array) $key){
// $key is now an array, recast to obj if you want
$objkey = (object) $key;
}
i'm assuming your using mysql since you did not say...
you can use thsi function mysql_fetch_object()
<?php
$trailheads = array()
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result, 'trailhead')) {
$trailheads[] = $row;
}
i am trying to create array like in the example i wrote above:
$arr=array('roi sabah'=>500,yossi levi=>300,dana=>700);
but i want to create it dynamic with foreach.
how can i do it ?
thanks.
You can access an array with foreach (and optionally create another one while going through the array's values). But if you only have data like a name and a number from your example, not stored in an array, you can't use foreach.
Another way to create the array you mentioned:
$arr = array();
$arr['roi sabah'] = 500;
$arr['yossi levi'] = 300;
// etc
And to access these values:
foreach ($arr as $key => $value) {
// $key is e.g. "roi sabah", and its value "500"
}