Adding to an associative array PHP - php

I have an array with three indexes which themselves are arrays:
$array['title'];
$array['description'];
$array['link'];
I need to add to this array in a loop.
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$array = $information['processed'];
}
The above works fine when I do it once without the loop, however I cannot add to $array.
What I have tried is:
$array = array();
$arraytemp = array();
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$arraytemp = $information['processed'];
$array = $array + $arraytemp; // the unique append as outlined in php manual
}
I have also tried:
$array = array();
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$array[] = $information['processed'];
}
And I have also tried:
$array = array();
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
array_push($array,$information['processed']);
}
For the application I am developing, I need a way of adding to this array whilst reserving the key structure. So I want to add the new information to the end of the array.
Creating a new dimension by doing something like the following is not appropriate for my program:
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$array[$i] = $information['processed'];
}
//The above is not appropriate for my application
Any ideas?
Thanks guys.

$array = array();
for ($i=0;$i<10;$i++)
{
$array[$i] = $information['processed'];
}

Related

php create arrays dynamically and merge

I'm trying to create an unknown number of arrays dynamically inside a foreach loop, merge them all at the end into one array, and use this in a JSON format for Google Analytics.
So far I have the following code which is throwing an error at the merge part:
$p=1;
foreach(...){
...
$arr = 'arr'.$p;
$name = $order->ProductGroupName;
$name = str_replace("'", "", $name);
$arr = array(
"name"=>$name,
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
$p++;
}
for ($q = 1; $q<$p; $q++){
$arry = 'arr'.$q;
$merge = array_merge($arry, $merge);
};
How do I create the arrays dynamically and merge them at the end, please?
I'm relatively new to PHP and have tried my best to get this to work.
I think I understand what you're trying to do. Just dynamically append [] to the array and you don't need to merge:
foreach($something as $order) {
$arr[] = array (
"name"=>str_replace("'", "", $order->ProductGroupName),
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
}
If you want to have string keys for whatever reason, then:
$p = 1;
foreach($something as $order) {
$arr["SomeText$p"] = array (
"name"=>str_replace("'", "", $order->ProductGroupName),
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
$p++;
}
And that's it. Check with:
print_r($arr);
Things like $arry = 'arr'.$q; stink of variable variables (though not done correctly) and shouldn't be used.

Is there a way to generate new array variables in a loop in PHP?

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;
}
}

Unset array element and reseting array values in PHP

So I have 2 files. In file 1 I have a table and there I randomly select some fields and store (store in session) them in an array of 2D arrays. When I click on the cell I send this data to my file 2 where I want to check if I clicked on a randomly selected array or not and if I did, I want to remove this 2D array from an main array.
But as soon as I click on one of the selected arrays, the array crashes.
File 1 PHP stuff immportant for this:
session_start();
$_SESSION['arrays'] = $stack ;
File 2 PHP:
session_start();
if (isset($_SESSION['arrays'])) {
$stack = $_SESSION['arrays'];
for ($i = 0; $i< count($stack);$i++){
if($cooridnates == $stack[$i]){
unset($stack[$i]);
array_values($stack);
$i--;
$Result = true;
break;
}
}
$_SESSION['arrays'] = $stack ;
I am suspecting the error might be in 2 things:
count($stack) used, but I don't believe this is the main reason.
The way I store session.
I have tried using manuals from W3Schools and official PHP website and also SOF, but with no use.
But still, I am not sure if the array_values() and unset() is working correctly since the thing chrashes and I can't test it correctly.
I would appreciate any tips.
You need to assign the result of array_values($stack); back to the $stack variable.
$stack = array_values($stack);
There's also no need to use $i-- when you do this, since you're breaking out of the loop after you find a match.
Instead of a loop, you can use array_search():
$pos = array_search($coordinates, $stack);
if ($pos !=== false) {
unset $stack[$pos];
$Result = true;
$stack = array_values($stack);
$_SESSION['arrays'] = $stack;
}
you can do this like that by using foreach loop:
session_start();
if (!empty($_SESSION['arrays'])) {
foreach( $_SESSION['arrays'] as $key => $val){
if($cooridnates == $val){
unset($_SESSION['arrays'][$key]); // if you want this removed value then assign it a variable before unsetting the array
$Result = true;
break;
}
}
}

Flatten RecursiveIteratorIterator array by children

I can't seem to figure out the best way to do this. I have a RecursiveIteratorIterator.
$info = new RecursiveIteratorIterator(
new GroupIterator($X), # This is a class that implements RecursiveIterator
RecursiveIteratorIterator::SELF_FIRST
);
Note: GroupIterator is a class that handles our custom formatted data
When I loop through it, I get exactly what I expect.
foreach($info as $data){
echo $info->getDepth().'-'.$data."\n";
}
The output is:
0-a
1-b
2-c
2-d
1-e
2-f
0-g
1-h
2-i
This is correct, so far. Now, what I want is to flatten the parents and children into a single array. I want one row for each max-depth child. The output I am trying to get is:
0-a 1-b 2-c
0-a 1-b 2-d
0-a 1-e 2-f
0-g 1-h 2-i
I can't figure out how to do this. Each iteration over the loop gives me another row, how can I combine the rows together that I want?
I managed to figure it out. #ComFreek pointed me in the right direction. Instead of using a counter, I used the current depth to check when I hit the lowest child, then I added the data to the final array, otherwise I added it to a temp array.
$finalArray = array();
$maxDepth = 2;
foreach($info as $data){
$currentDepth = $info->getDepth();
// Reset values for next parent
if($currentDepth === 0){
$currentRow = array();
}
// Add values for this depth
$currentRow[$currentDepth] = $data;
// When at lowest child, add to final array
if($currentDepth === $maxDepth){
$finalArray[] = $currentRow;
}
}
Try adding a counter variable:
// rowNr loops through 0, 1, 2
$rowNr = 0;
$curData = [];
$outputData = [];
foreach($info as $data){
// got last element, add the temp data to the actual array
// and reset temp array and counter
if ($rowNr == 2) {
$outputData[] = $curData;
$curData = [];
$rowNr == 0;
}
else {
// save temp data
$curData[] = $info->getDepth() . '-' . $data;
}
$rowNr++;
}

PHP array copy certain keys, built-in functions? Nested loop performance?

I have a PHP array that I'd like to duplicate but only copy elements from the array whose keys appear in another array.
Here are my arrays:
$data[123] = 'aaa';
$data[423] = 'bbb';
$data[543] = 'ccc';
$data[231] = 'ddd';
$data[642] = 'eee';
$data[643] = 'fff';
$data[712] = 'ggg';
$data[777] = 'hhh';
$keys_to_copy[] = '123';
$keys_to_copy[] = '231';
$keys_to_copy[] = '643';
$keys_to_copy[] = '712';
$keys_to_copy[] = '777';
$copied_data[123] = 'aaa';
$copied_data[231] = 'ddd';
$copied_data[643] = 'fff';
$copied_data[712] = 'ggg';
$copied_data[777] = 'hhh';
I could just loop through the data array like this:
foreach ($data as $key => $value) {
if ( in_array($key, $keys_to_copy)) {
$copied_data[$key] = $value;
}
}
But this will be happening inside a loop which is retrieving data from a MySQL result set. So it would be a loop nested within a MySQL data loop.
I normally try and avoid nested loops unless there's no way of using PHP's built-in array functions to get the result I'm looking for.
But I'm also weary of having a nested loop within a MySQL data loop, I don't want to keep MySQL hanging around.
I'm probably worrying about nested loop performance unnecessarily as I'll never be doing this for more than a couple of hundred rows of data and maybe 10 keys.
But I'd like to know if there's a way of doing this with built-in PHP functions.
I had a look at array_intesect_key() but that doesn't quite do it, because my $keys_to_copy array has my desired keys as array values rather than keys.
Anyone got any ideas?
Cheers, B
I worked it out - I almost had it above.I thought I'd post the answer anyway for completeness. Hope this helps someone out!
array_intersect_key($data, array_flip($keys_to_copy))
Use array_flip() to switch $keys_to_copy so it can be used within array_intersect_keys()
I'll run some tests to compare performance between the manual loop above, to this answer. I would expect the built-in functions to be faster but they might be pretty equal. I know arrays are heavily optimised so I'm sure it will be close.
EDIT:
I have run some benchmarks using PHP CLI to compare the foreach() code in my question with the code in my answer above. The results are quite astounding.
Here's the code I used to benchmark, which I think is valid:
<?php
ini_set('max_execution_time', 0);//NOT NEEDED FOR CLI
// BUILD RANDOM DATA ARRAY
$data = array();
while ( count($data) <= 200000) {
$data[rand(0, 500000)] = rand(0, 500000);
}
$keys_to_copy = array_rand($data, 100000);
// FOREACH
$timer_start = microtime(TRUE);
foreach ($data as $key => $value) {
if ( in_array($key, $keys_to_copy)) {
$copied_data[$key] = $value;
}
}
echo 'foreach: '.(microtime(TRUE) - $timer_start)."s\r\n";
// BUILT-IN ARRAY FUNCTIONS
$timer_start = microtime(TRUE);
$copied_data = array_intersect_key($data, array_flip($keys_to_copy));
echo 'built-in: '.(microtime(TRUE) - $timer_start)."s\r\n";
?>
And the results...
foreach: 662.217s
array_intersect_key: 0.099s
So it's much faster over loads of array elements to use the PHP array functions rather than foreach. I thought it would be faster but not by that much!
Why not load the entire result set into an array, then begin processing with nested loops?
$query_result = mysql_query($my_query) or die(mysql_error());
$query_rows = mysql_num_rows($query_result);
for ($i = 0; $i < $query_rows; $i++)
{
$row = mysql_fetch_assoc($query_result);
// 'key' is the name of the column containing the data key (123)
// 'value' is the name of the column containing the value (aaa)
$data[$row['key']] = $row['value'];
}
foreach ($data as $key => $value)
{
if ( in_array($key, $keys_to_copy))
{
$copied_data[$key] = $value;
}
}

Categories