Creating arrays in for loops - php

I'm starting with a csv variable of column names. This is then exploded into an array, then counted and tossed into a for loop that is supposed to create another array.
Every time I run it, it goes into this endless loop that just hammers away at my browser...until it dies. :(
Here is the code..
$columns = 'id, name, phone, blood_type';
$column_array = explode(',',$columns);
$column_length = count($column_array);
//loop through the column length, create post vars and set default
for($i = 0; $i <= $column_length; $i++)
{
$array[] = $iSortCol_.$i = $column_array[$i];
//create the array iSortCol_1 => $column_array[1]...
//$array[] = 'iSortCol_'.$i = $column_array[0];
}
What I would like to get out of all this is a new array that looks like so..
$goal = array(
"iSortCol_1" => "id",
"iSortCol_2" => "name",
"iSortCol_3" => "phone",
"iSortCol_4" => "blood_type"
);

Simply change
$array[] = 'iSortCol_'.$i = $column_array[0];
to
$array['iSortCol_'.$i] = $column_array[$i];
and the <= to < in your for loop, otherwise you will display a blank array value in your end result. Because you need to go up to but not including the length of $column_array.

$array[] = 'iSortCol_'.$i = $column_array[0];
I think it's because you're assigning the value of $column_array[0] to $i AND using it as the loop index. Use another variable to do that, otherwise it just goes on and on.
EDIT Tested and pasted output
Working code, just tested it on local
$columns = 'id, name, phone, blood_type';
$column_array = explode(',',$columns);
$column_length = count($column_array);
$array = array();
for($i = 0; $i < $column_length; $i++)
{
//create the array iSortCol_1 => $column_array[1]...
$array['iSortCol_'.$i] = $column_array[$i];
}
var_dump($array);
This will output
array
'iSortCol_0' => string 'id' (length=2)
'iSortCol_1' => string ' name' (length=5)
'iSortCol_2' => string ' phone' (length=6)
'iSortCol_3' => string ' blood_type' (length=11)
Is this not what you want?

I think you meant to write:
$array['iSortCol_'.$i] = $column_array[0];

Related

generate array for query string in php

Here I want to create an array for query string like given below:
item[]['item_id']=I00001&item[]['rate']=10.52&item[]['qty']=2&
item[]['item_id']=I52124&item[]['rate']=15.00&item[]['qty']=1&
item[]['item_id']=I62124&item[]['rate']=8.20&item[]['qty']=5
I want to generate it dynamically.
for($i = 0 ; $i< count($allitems) ;$i++){
$itemid = explode('~',$allitems[$i]);
$arrdet[]=["'item_id'"=>$itemid[0],"'rate'"=>$itemid[1],"'qty'" =>$itemid[2]];
$item['item'] = array_merge($arrdet);
//$item['item'][]=["'item_id'"=>$itemid[0],"'rate'"=>$itemid[1],"'qty'" =>$itemid[2]];
}
echo http_build_query($item);
but my result for this
item[0]['item_id']=I00001&item[0]['rate']=10.52&item[0]['qty']=2&
item[1]['item_id']=I52124&item[1]['rate']=15.00&item[1]['qty']=1&
item[2]['item_id']=I62124&item[2]['rate']=8.20&item[2]['qty']=5
How it Possible?
Thanks in advance
I did so much workarounds. But, it should actually works.
$countAllitems = count($allitems);
$arr = array();
$items = array();
$query = array();
for($i = 0 ; $i< $countAllItems; $i++){
$itemid = explode('~',$allitems[$i]);
$arr['item_id'] = $itemid[0];
$arr['rate'] = $itemid[1];
$arr['qty'] = $itemid[2];
//Assign the array to another array with key 'item[]'
$items['item[]'] = $arr;
//Build the array to http query and assign to another array
$query[] = http_build_query($items);
}
//Implode the stored http queries
echo implode('&', $query);
The array is zero-indexed internally.
$array = [1, 2, 3];
is internally
$array = [
0 => 1,
1 => 2,
2 => 3
]
The http_build_query will always output keys of the array, even if you do not specify them explicitly.

Concatenating multiple arrays to be inserted into a mongo aggregation query using php

I am trying to create an aggregation query for mongo within php. However I need to dynamically create the unwind operations. I am trying to do this within a for loop shown below.
for($j = 0; $j < $step; $j++) {
if($j == 0) {
$compare = '$steps'; //On first loop, instantiate the first level to unwind
} else {
$compare = $compare.".steps"; //Concatenate every next level to unwind
}
$wind = $wind.array('$unwind' => $compare); //Need a way to concatenate arrays
}
As you can see, I have tried to concatenate the arrays on every iteration, but this does not work.
Is there a way I can automate the creation of a variable containing the arrays below, depending on a number given for the number of unwinds needed - in the example below, the number is 3.
$wind = array('$unwind' => '$steps'), array('$unwind' => '$steps.steps'), array('$unwind' => '$steps.steps.steps'); //What I want end variable output to be
Final desired aggregation query below.
$query = array(
array(
'$match' => array(
"name" => $process['name'], $query => $title
)
),
$wind,
array(
'$project' => array(
"_id" => 0,
"steps.title" => 1,
)
),
);
EDIT: Solved, I used array_push to insert each part into the array. Seems I was making the problem way too complicated for myself.
You need array_merge. This function will merge your arrays. Example:
$wind = array();
for($j = 0; $j < $step; $j++) {
if($j == 0) {
$compare = '$steps'; //On first loop, instantiate the first level to unwind
} else {
$compare = $compare.".steps"; //Concatenate every next level to unwind
}
$wind = array_merge($wind, array('$unwind' => $compare)); //Need a way to concatenate arrays
}
Code is untested, let me know if there is any problem.

PHP Insert array into multidimensional array is overwrite

I´m trying to insert arrays into other array, the problem is that when I call the array_push() method it overwrites the last one element of my array, then I just get an array with data of one array (the last one):
$users_data = [];
$resultSize = count($result);
$data = $result;
for ($i = 0; $i < $resultSize; $i++) {
$person = [
'nombre' => $result[$i]['nombre'],
'apellido' => $result[$i]['apellido'],
];
array_push($users_data, $person);
// $users_data = $person; I also have tried with this method.
};
I just receive one object with this:
Object {nombre: jane, apellido: doe}
What is going wrong?
It shud be like this,
$person['nombre'][$i] = $result[$i]['nombre'];
$person['apellido'][$i] = $result[$i]['apellido'];
^ you have missed this index.
Then no need of array_push(). you can directly assign persons to user_data
Or like this :
for ($i = 0; $i < $resultSize; $i++) {
$users_data['nombre'][] = $result[$i]['nombre'];
$users_data['apellido'][] = $result[$i]['apellido'];
};

How to add variables that are passed on through the URL to an array?

<?php
$i = $_GET['i'];
echo $i;
$values = array();
while ($i > 0)
{
$expense = $_GET['expense_' + i];
$amount = $_GET['amount_' + i];
$values[$expense] = $amount;
i--;
print_r($values);
}
?>
i represents the number of sets of variables I have that have been passed through from the previous page. What I'm trying to do is add the expenses to the amounts and put them in an array as (lets just say for this example there were 3 expenses and 3 amounts) [expense_3 => amount_3, expense_2 => amount_2, expense_1 => amount_1]. The names of the variables are successfully passed through via the url as amount_1=50, amount_2=50, expense_1=food, expense2=gas, etc... as well as $i, I just dont know how to add those variables to an array each time.
Right now with this code I'm getting
4
Array ( [] => ) Array ( [] => ) Array ( [] => ) Array ( [] => )
I apologize if I'm not being clear enough, but I am pretty inexperienced with PHP.
The syntax error you're getting is because you're using i instead of $i - however - that can be resolved easily.
What you're looking to do is "simple" and can be accomplished with string-concatenation. It looks like you're attempting this with $_GET['expense'] + i, but not quite correct.
To properly build the parameter name, you'll want something like $_GET['expense_' . $i], here you can see to concatenate strings you use the . operator - not the + one.
I'm going to switch your logic to use a for loop instead of a while loop for my example:
$values = array();
for ($i = $_GET['i']; $i > 0; $i--) {
$expense = $_GET['expense_' . $i];
$amount = $_GET['amount_' . $i];
$values[$expense] = $amount;
}
print_r($values);
This is following your original logic, but it will effectively reverse the variables (counting from $i down to 1). If you want to count up, you can change your for loop to:
$numVariables = $_GET['i'];
for ($index = 1; $index <= $numVariables; $index++) {
$expense = $_GET['expense_' . $index];
...
Or just serialize the array and pass it to the next site, where you unserialize the array
would be much easier ;)

php looping through 2D array

I access the following values like this.
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[0]->Price
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[0]->Low
//next row
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[1]->Price
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[1]->Low
However I need to consolidate this to
$values[0][price]
$values[0][low]
$values[1][price]
$values[1][low]
2 other strange things. The values are strings and I need them to be decimals(2 decimal points) and also the min and the max for price and low accross all the rows
Well the obvious way to build an array of values would be:
$values = array();
for($i = 0; $i < some_maximum_value; $i++) {
$values[$i] = array(
'price' => $result->{'HistoricalPricesResult'}->HistoricalPricesResult[$i]->Price,
'low' => $result->{'HistoricalPricesResult'}->HistoricalPricesResult[$i]->Low,
);
}
TADAAAAAA!!!!
$values = array();
foreach($result->{'HistoricalPricesResult'}->HistoricalPricesResult as $key => $obj){
$values[$key]['price'] = $obj->Price;
$values[$key]['low'] = $obj->low;
}
$myVals = array();
foreach ($result->{'HistoricalPricesResult'}->HistoricalPricesResult as $key => $v)
{
$myVals[$key]['price'] = 1.0 * $c->Price; //hoping string has 2 after the decimal
$myVals[$key]['low'] = 1.0 * $c->Low
}
Try to figure out max/min yourself
Check out foreach loops and string/float conversion
http://us2.php.net/manual/en/control-structures.foreach.php
http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion

Categories