array to variables - php

I'm programming in PHP and I have a huge array which contains a lot of ID's. I need all these ID's to be variables so I can use these in another function. I have done a lot of research on loops in PHP but I can find one which "converts" the arrays into variables that I can use in another function. So far I have a foreach loop which processes the whole array and divided into $persons. But when I use $persons in the next function it only uses the last array. My code is as follows:
$retrieved_id_array=explode(",",$retrieved_id_string);
foreach($retrieved_id_array as $persons)
$retrieved_string=file_get_contents("https://HDXLfansite.com/$persons");
So the problem is how do I make a loop which provides me with several variables I can use in another function? Or should I use another method/code?

thats because you are overwriting your variable $retrieved_string in loop, you could do:
foreach($retrieved_id_array as $persons) {
//add it in array
$retrieved_string[] =file_get_contents("https://HDXLfansite.com/$persons");
}

Related

Alternative way of accessig an array within array in PHP

I'm trying to access an array within another array (basically, a two dimensional array). However, the usual way of doing this ($myarray[0][0]) doesn't work for me.
The reason is because I want to create a recursive function which, in each call, should dive deeper and deeper into a array (like, on first call it should look at $myarray[0], on second call it should look at $myarray[0][0] and so on).
Is there any alternative way of accessing an array within array?
Thanks.
Traverse the array by passing always a subarray of it to the recursive function.
function f(array &$arr)
{
// Some business logic ...
// Let's go into $arr[0]
if(is_array($arr[0]))
f($arr[0]);
}
f($myarray);

Is it safe to add new keys to an array while iterating over it?

For example, is this safe?
foreach($opps_data as $k=>$v) {
$opps_data[$k.'_mixed'] = WXU::MixedCase($v);
}
It seems to work fine. Does that mean PHP makes a copy of the array before it starts looping?
Yes, foreach loop operates on a copy of original array. More info about internal behaviour of foreach can be found in this great blog.
foreach() uses iterators. Array is called then iterator is used for pointing to array which was called.
In this case $opps_data is called only once. Iterator will not reference original array it will be working on copy of $opps_data which was called.

PHP how to optimize writing to file in this situation

To better explain you my situation I will both describe it and supply corresponding pseudo-code(sort of). I'm in a dilemma and need some help.
So I have this function which is called upon consecutively and frequently. In the function I have a for loop which executes a variable number of times, based on supplied data. In that for loop there is an array which gets populated with all of that data. Still in the function, when the for loop ends, the array gets written into a CSV file. And then execution stops. However as I mentioned the function gets called frequently one call after the other, this results in repeated steps of populating the array in the loop and then writing into the file. The pseudocode illustrates this situation better(not my actual code, just mockup):
-call function stuff n times
//Paragraph2 solution? -- global array declaration here ?
function stuff
{
for loop(conditions)
{
array <= data
}
array => file // Paragraph2 solution? -- Global array <= loop arrays
}
// Paragraph2 solution? -- Global array => write to file
This works just fine. The problem lies in the speed of writing to the file. I think it is impaired because of all the little arrays that constantly get written into the file. I want to make all these arrays in the for loop to write their data into a global array outside the loop so that I can just take this one array with all the data and insert it in the CSV file, so I would have just one transaction to the file instead of the countless transactions that I had before. So, is this what I thought of possible, is it correct, or is there a better way of doing this? And can you please supply usable code in you answer. Thank You.
This is how you can use a global array inside the function
$stuff = array();
function add_stuff($new_stuff)
{
global $stuff;
$stuff[] = $new_stuff;
}
add_stuff("hello");
add_stuff("world");
print_r($stuff);
the output should be:
Array
(
[0] => hello
[1] => world
)

Creating an associative array from an array, based on the array - PHP

I have a unique issue that I have never heard of this being possible to do before:
So essentially I have a function that takes in a an array of arguments such as:
function someFunction(array $arguments){}
and gives me an array back as such:
array('option1', 'option2', 'options3', ...);
I then need to take that array and loop through it creating an associative array such as:
array('option1' => call_come_method('option1'), .... );
heres the kicker, you will never know how many arguments a user passes into the function, yet each one needs to created into a key=>value arrangement as seen above.
Now i did some research and I was told the $argv command in php, how ever where I am stumped is how to implement it in this case.
So if any one can give me any pointers I would be appreciative.
This is a lot easier than you think. First use array_flip to switch the array's keys and values.
$newArray = array_flip($arguments);
Then loop though it and call the method:
foreach($newArray as $key=>&$val){
$val = call_come_method($key);
}
The &, makes it a reference, so the array value is updated.
DEMO: http://codepad.org/giL1KPA3
UPDATE: You don't even need array_flip, you just need a for loop.
$newArray = array();
foreach($arguments as $val){
$newArray[$val] = call_come_method($val);
}
DEMO: http://codepad.org/AQ1gWrou
you will never know how many arguments a user passes into the function
FYI, you get to know it with func_get_args().
This way you don't need to provide your function with an $arguments parameter, but you just leave it empty.

PHP scope question

I'm trying to look through an array of records (staff members), in this loop, I call a function which returns another array of records (appointments for each staff member).
foreach($staffmembers as $staffmember)
{
$staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
// print_r($staffmember['appointments'] works fine
}
This is working OK, however, later on in the script, I need to loop through the records again, this time making use of the appointment arrays, however they are unavailable.
foreach ($staffmembers as $staffmember)
{
//do some other stuff
//print_r($staffmember['appointments'] no longer does anything
}
Normally, I would perform the function from the first loop, within the second, however this loop is already nested within two others, which would cause the same sql query to be run 168 times.
Can anyone suggest a workaround?
Any advice would be greatly appreciated.
Thanks
foreach iterates over a copy of the array. If you want to change the value, you need to reference it:
foreach($staffmembers as &$staffmember) // <-- note the &
{
$staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
// print_r($staffmember['appointments'] works fine
}
From the documentation:
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
and
As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

Categories