Note, array_chunk is not my solution (It seems to me).
I have an array of about 150.000 elements
Array
(
[0] => Array
(
[name] => Danilo
[phone] => 33568
)
[1] => Array
(
[name] => Alessandro
[phone] => 392222
)
[2] => Array
(
[name] => Alex
[phone] => 3922
)
[3] => Array
(
[name] => Capa
[phone] => 392
)
)
And so on. I would split this array in several arrays, of (for example) 3.000 elements every one.
I saw array_chunk, but it returns a single array with several subarray.
I need several subarray to store them in a database and elaborate in future.
I'm getting crazy to write a snippet starting from that $temp and divide it into smaller array.
$size_chunks = 1;
$temp = array_chunk($recipients, $size_chunks);
foreach ($temp as $key=>$value)
{
if ($key<$size_chunks)
{
$to_store[] = $temp[$key];
}
//print_r($to_store);
// pseudo sql
// INSERT INTO table (sub_recipient) VALUES ($to_store);
$to_store = array();
}
So, every time that for loop end, reduce temp, store $to_store array and restart for others chunks.
Thank you very much.
PS in my example chunk==1 because starting array is small... ;)
With my example of chunk = 1, I need from starting array this 4 arrays:
Array
(
[0] => Array
(
[name] => Danilo
[phone] => 33568
)
)
Array
(
[0] => Array
(
[name] => Alessandro
[phone] => 39222
)
)
Array
(
[0] => Array
(
[name] => Alex
[phone] => 39222
)
)
Array
(
[0] => Array
(
[name] => Capa
[phone] => 392
)
)
Another explain
1 - With a starting array of 15.000 elements, and chunk of 3.000, I need in output (15.000 / 3.000) = 5 arrays. I will save them in database, so in DB I will have 5 rows (a row for every array).
2 - With a starting array of 4 elements, and chunk of 1, I need in output (4 / 1) = 4 arrays. I will save them in database, so in DB I will have 4 rows (a row for every array).
array_chunks() already does what you want, you just have to save it:
$chunks = array_chunk($array, $size_chunks);
foreach ($chunks as $chunk) {
// save $chunk to your database
}
$recipients = Array(
Array("fdbvfdb","dsacsdcds"),
Array("hrloo","dacdsc"),
Array("dcsdc","adcsd"),
Array("dcsdc","adcsd")
);
$total = count($recipients);//count 150.000 elements
$i=1;
for($i=0;$i<$total;$i++){
$O = array_slice($recipients,$i,1);
print_r($O);
//Your insert/Save code
}
you can use this code there is uses Array_Slice
Related
I want to merge two arrays in order to get the data as per my requirement.
I am posting my result, please have a look.
First array:
Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
)
)
Second array:
Array
(
[0] => Array
(
[user_id] => 9c2e00508cb28eeb1023ef774b122e86
[car_id] => 14783
[status] => favourite
)
)
I want to merge the second array into the first one, where the value at key car_id matches the equivalent value; otherwise it will return that field as null.
Required output:
<pre>Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
[fav_status] => favourite
)
)
Since the merge is so specific I would try something like this:
foreach ($array1 as $index => $a1):
foreach ($array2 as $a2):
if ($a1['car_id'] == $a2['car_id']):
if ($a2['status'] == "favourite"):
$array1[$index]['fav_status'] = "favourite";
endif;
endif;
endforeach;
endforeach;
You might be able to optimize the code more but this should be very easy to follow...
Another way to achieve this without using the index syntax is to reference the array elements in the foreach by-reference by prepending the ampersand operator:
foreach($firstArray as &$nestedArray1) {
foreach($secondArray as $nestedArray2) {
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1['fav_status'] = $nestedArray2['status'];
}
}
}
You can see it in action in this Playground example.
Technically you asked about merging the arrays. While the keys would be different between the input arrays and the desired output (i.e. "status" vs "fav_status"), array_merge() can be used to merge the arrays.
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 = array_merge($nestedArray1, $nestedArray2);
}
Playground example.
Additionally the union operators (i.e. +, +=) can be used.
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator1
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 += nestedArray1;
}
Playground example.
1http://php.net/manual/en/function.array-merge.php#example-5587
This question already has answers here:
Generate an associative array from an array of rows using one column as keys and another column as values
(3 answers)
Closed 7 months ago.
I have an array of array that looks like this:
Array
(
[0] => Array
(
[id] => I100
[name] => Mary
[gender] => F
)
[1] => Array
(
[id] => I101
[name] => John
[gender] => M
)
[2] => Array
(
[id] => I245
[name] => Sarah
[gender] => F
)
)
I want to set the key of the parent array with the value of id, so the result array looks like this:
Array
(
[I100] => Array
(
[id] => I100
[name] => Mary
[gender] => F
)
[I101] => Array
(
[id] => I101
[name] => John
[gender] => M
)
[I245] => Array
(
[id] => I245
[name] => Sarah
[gender] => F
)
)
If possible I'd like to avoid using an additional loop to go through the array and creating a new array to store each item with the proper key, as the array can have thousands of items.
Thanks in advanced!
Despite your caveat, a loop is the obvious solution:
$newArray = [];
foreach($oldArray as $item)
$newArray[$item['id']] = $item;
If the problem you have is not specifically with a loop, but rather creating a copy of the array is causes excessive memory consumption, then you can edit the array in place, with a for loop:
for($i=0; $i<count($oldArray); $i++){
$oldArray[$oldArray[$i]['id']] = $oldArray[$i];
unset($oldArray[$i]);
}
Note this works because the id elements are alphanumeric strings, if they where simple integars then the above code could overwrite sections.
The only other solution is to build the correct array in the 1st place, in a similar manner.
For example, using PDO::fetch instead of PDO::fetchAll:
//$newArray = $sth->fetchAll(PDO::FETCH_ASSOC);
$newArray = [];
while($row = $sth->fetch(PDO::FETCH_ASSOC))
$newArray[$row['id']] = $row;
You can't overwrite keys while iterating through an array "on the fly". So here is solution with array_map which produces an array with needed structure:
// assuming $arr is your initial array
$result = [];
array_map(function($a) use (&$result){
$result[$a['id']] = $a;
}, $arr);
// $result contains the needed array
You can add needed key during creation of this array.
I'm trying to access multiple values in multiple foreach loops outside of the loops:
foreach(array1 as arr1) {
$var1 = arr2['value1']; //$array is associative array with mutliple keys value1
}
Then I have another
foreach(array2 as arr2) {
$var2 = arr2['value']; //$array2 is another associative array with multiple keys value
}
All of this is within another big foreach loop and now I want to create an array within the big foreach with $var1 and $var2 being used. This array I'm going to be creating is going to be an associative array as well. Any ideas how I can do this?
Array 1:
Array
(
[0] => Array
(
[id] => 1
[id_name] => 251452
[name] => bob
)
[1] => Array
(
[id] => 2
[id_name] => 251453
[name] => bob
)
)
Array 2:
Array
(
[0] => Array
(
[id_person] => 4
[id_last_name] => 251452
[last_name] => smith
)
[1] => Array
(
[id_person] => 15
[id_last_name] => 251453
[last_name] => johnson
)
)
Assume these come from two different queries from the database.
I want to get the first name from the first array for each one and get the last name from the second array for each one and make one array that has this data along with others.
Have a look into multi dimensional arrays.
Also have a look at stdclass and maybe creating an array of these which can store many variables within a single definition - which can help in many ways. (standard class)
Nested looping - this would just dump all sub arrays into an object
// Object and array examples for an InnerArray
$Object = new stdclass();
$AllOfIt = array();
$cnt = 0;
foreach($OuterArray as $OuterKey => $InnerArray)
{
$cnt++;
foreach($InnerArray as $InnerKey => $InnerValue)
{
$Object->$cnt = $InnerValue;
$AllOfIt[$cnt] = $InnerValue;
}
}
I have an array which looks like this:
Array
(
[0] => Array
(
[1] => Array
(
[name] => vrij
// ...
)
[2] => Array
(
[name] => zat
// ...
)
)
)
I build this array using a for loop; however, I need to push 4 more 'records' to the array, which I can't do in this for loop.
I want the array to look like this, after the pushes:
Array
(
[0] => Array
(
[1] => Array
(
[name] => vrij
// ...
)
[2] => Array
(
[name] => zat
// ...
)
// ...
)
[1] => Array
(
[1] => Array
(
[name] => zon
//...
)
[2] // etc
)
)
The four new records should be pushed to array[1], so I get something like
$array[1][0], $array[1][1], etc. 0 1 2 3 contains the new data.
I tried quite a lot of stuff, to be honest. I need to do four of these pushes, so I was trying a for loop:
for($i = 0; $i < 4; $i++)
{
$day_info = $this->get_day_info($i, $data['init']['next_month'], $data['init']['current_year']);
$push['name'] = $day_info['day_name'];
array_push($data['dates'], $push);
}
and all other kinds of things with [], [1][$i], etc. Sometimes it even adds five arrays! I'm confused as to why it won't just add the [1][1], [1][2],.. I'm probably missing out on something here. Thanks a lot.
If this isn't clear, please do tell and I'll add more code to explain the problem better.
$extradates = array(1 => 'zon', 2 => 'maa');
$data['dates'][] = $extradates;
Will add 2 extra dates to the array using a new index.
Although if I see what you trying to accomplish, I think there might be a better way.
This above works though :)
I'm grabbing a some XML data and parsing it with PHP.
Most of the results come in multidimensional array but occasionally I'll get a result in a single array and it breaks my script.
I'm trying to format the single result to match the format of the results in the multidiminsonal array but I'm not having any luck.
Here is what I got:
Array
(
[name] => Steve Jobs
[id] => 3
)
Array
(
[0] => Array
(
[name] => Steve Jobs
[id] => 6
)
[1] => Array
(
[name] => Bill Gates
[id] => 8
)
)
I'm trying to format the single result to match the multidimensional format then flatten...
Array
(
[0] => Array
(
[name] => Steve Jobs
[id] => 3
)
[1] => Array
(
[name] => Steve Jobs
[id] => 6
)
[2] => Array
(
[name] => Bill Gates
[id] => 8
)
)
I've tried this:
$array_check = #array_keys($result[0]['name']);
if ($array_check[0] == "0") {
$result;
} elseif ($array_check[0] == "name") {
$ReWrite = array ([0] =>
array (['name']=>
array ($result[0]['name'])
));
$result = $ReWrite;
}
I thought that would do it but it's off...
Try this:
$array_check = #array_keys($result[0]['name']);
if (!isset($array_check[0])) {
$result[] = $array_check;
} else {
$result = $array_check;
}
var_dump($result);
If your first array was assigned to the variable $singleArray and your target results stored in $results, try this array_push($results, $singleArray);
Use this together with reset() it returns the first element of an array:
if(!is_array(reset($result))){
array_push($results, $result);
}
This will test if the array does not contain an array as an element, if it doesn't push the whole array to an aggregate array.
Edit: Try this loop:
for($i = 0; $i <= count($multi); $i++){
$arr = $multi[$i];
if(!is_array($arr)){
$multi[$i] = array($arr);
}
} var_dump($multi);