Php Loop with a List - php

I have a PHP code like that:
$cityCount=10;
$currentUsers = array();
$addedUsers = array();
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
$currentUsers[$cityId] = array();
$addedUsers[$cityId] = array();
}
However, I want to change the for and I want to define an array for cities because new city will be added and it'i city id will be 22(not 11. If it could be 11 there was going to be just one change at code $cityCount=11; but city id is not sequential now.)
As like:
[1,2,3,4,5,6,7,8,9,10,22]
I want to iterate over that array.
Also I have a code like that:
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
foreach ($addedUsers[$cityId] as $userId) {
if($added) $addSql .= ",\n";
$addSql .= '(' . $userId . ", " . $cityId . ')';
$added++;
}
How to change this code according to new version of code?

$citiesids = array(1,2,3,4,5,6,7,8,9,10,22);
$currentUsers = array();
$addedUsers = array();
foreach ($citesids as $cityId) {
$currentUsers[$cityId] = array();
$addedUsers[$cityId] = array();
}
is that what you need?

Use foreach:
$cities = array(1,2,3,4,5,6,7,8,9,10,22);
foreach ($cities as $cityId) {
// use $cityId as before.
}

I'm not really sure what you mean exactly, but perhaps you mean using the array of cityIds instead of a simple counter?
In that case, simply use a foreach:
foreach ($cities as $cityId)

I assume you want to iterate over cities, but not all of them
$cityCount=22;
$cities = array(1,2,3,4,5,6,7,8,9,10,22);
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
// only handle the cases that where cityid is in the cities-array
if (!in_array($cityId, $cities)) continue;
// do what you like here
}

$cityCount=10;
$currentUsers = array();
$addedUsers = array();
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
$currentUsers[$cityId] = array();
array_push($addedUsers,$cityId);
}
echo '<pre>';
print_r($addedUsers);
echo '</pre>';
array_push($addedUsers,22);//whatever city you want to added (22 for example)
echo '<pre>';
print_r($addedUsers);
echo '</pre>';
OUTPUT
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 22 // just Added
)

As I suspected, it should be SQL query, not PHP code
Something like
select * from user WHERE where city IN (SELECT * FROM cities)
or whatever suits your hidden and secret needs

Related

Looping through array and get non-repeating values

I have an array of elements which I queried from the mongoDB.
This array has the id of a device and value of this device's consumptions.
For example there are 3 different ids -> 18,5,3 and multiple mixed values.
// first record of 18 so get value.
$row[0]["id"] = 18;
$row[0]["value"] = 100;
// not first record of 18 so ignore and move to the next record
$row[1]["id"] = 18;
$row[1]["value"] = 40;
// first record of 5 so get value.
$row[2]["id"] = 5;
$row[2]["value"] = 20;
// not first record of 18 so ignore and move to the next record
$row[3]["id"] = 18;
$row[3]["value"] = 30;
// first record of 3 so get value.
$row[4]["id"] = 3;
$row[4]["value"] = 20;
//not first record of 5 so ignore and move to the next record**
$row[5]["id"] = 5;
$row[5]["value"] = 30;
// not first record of 18 so ignore and move to the next record
$row[6]["id"] = 18;
$row[6]["value"] = 10;
...
....
What I am trying to do is loop through this $row array and get the most recent value of the id.
For example in above example what I want to return is:
id value
18 100
5 20
3 20
How can I do that kind of logic?
It can be done in several ways. The easiest one is to use a foreach:
$result = array();
foreach ($row as $i) {
if (! array_key_exists($i['id'], $result)) {
$result[$i['id']] = $i['value'];
}
}
# Verify the result
print_r($result);
The output is:
Array
(
[18] => 100
[5] => 20
[3] => 20
)
The same processing, but using array_reduce():
$result = array_reduce(
$row,
function(array $c, array $i) {
if (! array_key_exists($i['id'], $c)) {
$c[$i['id']] = $i['value'];
}
return $c;
},
array()
);
If you want to keep only the first occurrence of each 'id' then just add the values to an aggregate array - but only if they haven't been added already. Then grab the values of the aggregate array.
https://tehplayground.com/NRvw9uJF615oeh6C - press Ctrl+Enter to run
$results = array();
foreach ($row as $r) {
$id = $r['id'];
if (! array_key_exists($id, $results)) {
$results[$id] = $r;
}
}
$results = array_values($results);
print_r($results);
Array
(
[0] => Array
(
[id] => 18
[value] => 100
)
[1] => Array
(
[id] => 5
[value] => 20
)
[2] => Array
(
[id] => 3
[value] => 20
)
)
Try this
$alreadyfound = []; // empty array
$result = [];
foreach ($row as $item)
{
if (in_array($item["id"], $alreadyfound))
continue;
$alreadyfound[] = $item["id"]; // add to array
$result[] = $item;
}
The result
Array
(
[0] => Array
(
[id] => 18
[value] => 100
)
[1] => Array
(
[id] => 5
[value] => 20
)
[2] => Array
(
[id] => 3
[value] => 20
)
)
The array_unique() function is exactly what you are looking at.
See the documentation here : array_unique() documentation
Using array_column with an index key will almost do it, but it will be in the reverse order, so you can reverse the input so that it works.
$result = array_column(array_reverse($row), 'value', 'id');

Appending each item in an array with multiple suffixes then make new array

I am trying to run an array through a for loop to append the items checked onto each array with each one appending the suffix with $n (1-3). Thank you for your suggestions I am one step closer, now I am getting each suffix on one item. I want each one as its own item in the array. Can anyone see the error?
I have updated my code and it is one step closer to the solution and underneath it is what I am aiming for.
$equip = 'Phone';
$ailments_checkvar = explode(', ', 'Cracked, Scratched, Bent, Twisted');
foreach ($ailments_checkvar as &$value) {
$value = 'directory/'.$equip.'_'.$value.'';
}
unset($value);
$duplicateArray = $ailments_checkvar;
foreach ($ailments_checkvar as $key) {
$duplicateArray[] = $key;
}
foreach ($ailments_checkvar as $key) {
$duplicateArray[] = $key;
}
for ($n = 1; $n <= 3; $n++) {
foreach ($duplicateArray as &$valueN) {
$valueN = $valueN.'_0'.$n.'.pdf';
}
}
unset($valueN);
print_r ($duplicateArray);
Getting this
Array ( [0] => directory/Phone_Cracked_01.pdf_02.pdf_03.pdf
[1] => directory/Phone_Scratched_01.pdf_02.pdf_03.pdf
[2] => directory/Phone_Bent_01.pdf_02.pdf_03.pdf
[3] => directory/Phone_Twisted_01.pdf_02.pdf_03.pdf
[4] => directory/Phone_Cracked_01.pdf_02.pdf_03.pdf
[5] => directory/Phone_Scratched_01.pdf_02.pdf_03.pdf
[6] => directory/Phone_Bent_01.pdf_02.pdf_03.pdf
[7] => directory/Phone_Twisted_01.pdf_02.pdf_03.pdf
[8] => directory/Phone_Cracked_01.pdf_02.pdf_03.pdf
[9] => directory/Phone_Scratched_01.pdf_02.pdf_03.pdf
[10] => directory/Phone_Bent_01.pdf_02.pdf_03.pdf
[11] => directory/Phone_Twisted_01.pdf_02.pdf_03.pdf
)
And want to make this...
Array (
[0] => directory/Phone_Cracked_01.pdf
[1] => directory/Phone_Cracked_02.pdf
[2] => directory/Phone_Cracked_03.pdf
[3] => directory/Phone_Scratched_01.pdf
[4] => directory/Phone_Scratched_02.pdf
[5] => directory/Phone_Scratched_03.pdf
[6] => directory/Phone_Bent_01.pdf
[7] => directory/Phone_Bent_02.pdf
[8] => directory/Phone_Bent_03.pdf
[9] => directory/Phone_Twisted_01.pdf
[10] => directory/Phone_Twisted_02.pdf
[11] => directory/Phone_Twisted_03.pdf
)
for ($z=1;$z<=count($ailments_checkvar);$z++) {
$ailments_checkvar[$z-1] = $ailments_checkvar[$z-1].'_0'.$z.'.pdf';
}
unset($z);
what ever u did was causing the stack problem for $ailments_checkvar
please check out this is optimized code.
your error lies in $valueN = $ailments_checkvar.'_0'.$n.'.pdf';
Look at this statement here,
$valueN = $ailments_checkvar.'_0'.$n.'.pdf';
^^^^^^^^^^^^^^^^^^
$ailments_checkvar is an array, not a string. In the above statement, you're trying to convert an array to a string. It should be,
$valueN = $valueN.'_0'.$n.'.pdf';
Update(1):
Based on the requirement you posted above, the solution would be like this:
$equip = 'Phone';
$ailments_checkvar = explode(', ', 'Cracked, Scratched, Bent, Twisted');
$path_array = array();
foreach($ailments_checkvar as $property_status){
for($i = 1; $i <= 3; ++$i){
$path_array[] = 'directory/' . $equip . '_' . $property_status . '_0' . $i . '.pdf';
}
}
echo '<pre>'; print_r ($path_array);
Here's the live demo.

Dynamic associative Array - list, count, sum, min, max

I've got an array with about 40 keys. I'd like to have a small function that returns a summary array.
Right now I've got the following that works:
foreach ($all_data as $value){
$new_array[ $value['location'] ][ $value['manufacturer'] ][ $value['model'] ] += 1;
}
This returns an array with everything I need. However, the location, manufacturer and model could be changed up for a bunch of other values.
what I am trying to do is have something simple as:
$new_array = summarize($all_data,array('location','manufacturer','model','count'),array('list','list','list','count') );}
where this summarize function would build the call. I think I just need a bit of help on how to get it to run the string as code for this array. Otherwise I get
$current_selection = "[ $row_item['location'] ][ $row_item['manufacturer'] ][ $row_item['model'] ]"
$return_array{$current_selection} += 1;
Where the end goal is to have a function like:
function summarize($data_array, $fields_array, $process_array){
//data_array = associative multi-dimensional data array
//fields = values to pull from the data_array
//process = array specifying whether to list, sum, count, average, max, min
$return_array = array();
$current_selection = "";
foreach($fields_array as $field){
$current_selection .= '[ $row_item[\'' . $field . '\'] ]';
}
foreach ($data_array as $row_item){
//dynamic = DOES NOT WORK
$return_array[$current_selection] += 1;//eval? create function? abstract?
//another attempt
${'return_array' . $current_selection} += 1;
//Manual = Does work
//$return_array[ $row_item['location'] ][ $row_item['manufacturer'] ][ $row_item['model'] ] += 1;
}
}
Thanks for any help on how to do an indirect reference.
JC
RESOLUTION
The final version that managed to resolve this looks like the following, thanks to user: check, for getting me on the correct path.
function summarize($data_array, $fields_array, $process_array){
$return_array = array();
$i = 0;
foreach ($data_array as $row){
$ii = 0;
$temp = array();
$temp2 = array();
foreach($fields_array as $key=>$field){
if($process_array[$ii] == 'list') $temp[$ii] = $row[$field];
if($process_array[$ii] == 'count') $temp2[$ii] = 1;
if($process_array[$ii] == 'sum') $temp2[$ii] = $row[$field];
$ii++;
}
$unique = true;
$ii = 0;
foreach($return_array as $row2){
if(array_intersect_key($row2,$temp) == $temp){//$row2 == $temp){
$unique = false;
break;
}
$ii++;
}
if($unique){
$return_array[$i] = $temp;
if(!empty($temp2)) $return_array[$i] = array_merge($temp,$temp2);
$i++;
}else{
if(!empty($temp2)){
foreach($temp2 as $key => $value){
if($process_array[$key] == 'sum') $temp2[$key] = $return_array[$ii][$key] + $value;
if($process_array[$key] == 'count') $temp2[$key] = $return_array[$ii][$key] + 1;
if($process_array[$key] == 'max') $temp2[$key] = ($return_array[$ii][$key] < $value) ? $value : $return_array[$ii][$key];
if($process_array[$key] == 'min') $temp2[$key] = ($return_array[$ii][$key] > $value) ? $value : $return_array[$ii][$key];
//TODO:(JC) 'average' - need to create a count field if not present (or always despite and assume overhead of extra computations).
// - then just calculate the 'sum' and divide by the counter as a last step before returning the array.
}
$return_array[$ii] = array_merge($temp,$temp2);
}
}
}
print_r($return_array);
return $return_array;
}
Which gives the following result:
/*
CALL: summarize($data,array('location','manufacturer','model','model','volume','colourvolume'),array('list','list','list','count','sum','sum') );
[0] = location
[1] = manufacturer
[2] = model
[3] = model count
[4] = mono volume sum
[5] = colour volume sum
*/
Array
(
[0] => Array
(
[0] =>
[1] => HP
[2] => LaserJet 4000
[3] => 3
[4] => 3000
[5] => 0
)
...
[17] => Array
(
[0] => Room 114
[1] => CANON
[2] => iR3235
[3] => 1
[4] => 4012
[5] => 0
)
[18] => Array
(
[0] => Room 115
[1] => LEXMARK
[2] => T652
[3] => 1
[4] => 20
[5] => 0
)
)
alternatively, if I assume that's $field_array contains sequentially key fields from root to sub key, you can loop your $field_array within $data_array loop
function summarize($data_array, $fields_array, $process_array){
$return_array = array();
foreach ($data_array as $row){
$temp = array();
foreach($fields_array as $key=>$field){
$temp = $key==0?$row[$field]:$temp[$field];
}
if(!empty($temp)) $return_array[] = $temp;
}
return $return_array;
}
and this is my array, will summarize with these function
$array = array(
array("multi"=>array("dimensional"=>array("array"=>"foo1"))),
array("multi"=>array("dimensional"=>array("array"=>"foo2"))),
array("multi"=>array("dimensional"=>array("array"=>"foo3"))),
array("multi"=>array("dimensional"=>array("array"=>"foo4"))),
array("multi"=>array("dimensional"=>array("array"=>"foo5"))),
array("multi"=>array("dimensional"=>array("array"=>"foo6"))),
array("multi"=>array("dimensional"=>array("array"=>"foo7"))),
array("multi"=>array("dimensional"=>array("array"=>"foo8"))),
array("multi"=>array("dimensional"=>array("array"=>"foo9")))
);
print_r(summarize($array,array("multi","dimensional","array"),NULL));
Ouput
Array ( [0] => foo1 [1] => foo2 [2] => foo3 [3] => foo4 [4] => foo5 [5] => foo6 [6] => foo7 [7] => foo8 [8] => foo9 )

Merging arrays that are inside a foreach loop using PHP

I have following array:
Array
(
[0] => ALFA01
[1] => BETA02
[2] => GAMMA03
[3] => DELTA04
[4] => EPSILON05
[5] => ZETA06
[6] => THETA07
[7] => IOTA08
[8] => KAPPA09
[9] => LAMBDA10
)
Then I separate the values into characters and numbers in the following way:
foreach($portfolio as $value) {
$char = substr("$value", 0, 2);
$numb = substr("$value", 2);
and do a query using this values:
$query = "
SELECT id, typ1, typ2, typ3
FROM data_table
WHERE char = '$char'
AND numb = $numb
LIMIT 1";
$result = mysqli_query($mysqli, $query);
//Now we have some important variables that will help finding our result.
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$typ1 = $row['typ1'];
$typ2 = $row['typ2'];
$typ3 = $row['typ3'];
}
Then I do some queries in case typ* are = 1 (it can be only 0 or 1).
if ($typ1 == 1) {
$query_id_num2 = "
SELECT id_num2
FROM values_table01
WHERE id_num1 = $id";
$result_id_num2 = mysqli_query($mysqli, $query_id_num2);
// Return an array with all ids.
$id_num2_typ01 = array();
while($row = mysqli_fetch_array($result_appln_id_num2)) {
$id_num2_typ01[] = ($row['id_num2']);
}
}
/== EDIT ==/
In each different typ we have a different values_table.
I'm now writing the complete query for typ2, so it will be emphasised.
// == /EDIT ==/
Then I do the same to typ2 and typ3...
if ($typ2 == 1) {
$query_id_num2 = "
SELECT id_num2
FROM values_table02
WHERE id_num1 = $id";
$result_id_num2 = mysqli_query($mysqli, $query_id_num2);
// Return an array with all ids.
$id_num2_typ02 = array();
while($row = mysqli_fetch_array($result_appln_id_num2)) {
$id_num2_typ02[] = ($row['id_num2']);
}
}
etc.
In the end I merge the three arrays (if they are set) and print the result on the screen:
// typ01
if (isset($id_num2_typ01)){
$id_num2_typ01 = $id_num2_typ01;
} else {
$id_num2_typ01 = array();
}
// typ02
if (isset($id_num2_typ02)){
$id_num2_typ02 = $id_num2_typ02;
} else {
$id_num2_typ02 = array();
}
// typ03
if (isset($id_num2_typ03)){
$id_num2_typ03 = $id_num2_typ03;
} else {
$id_num2_typ03 = array();
}
// merge arrays
$id_num2 = array_merge($id_num2_typ01,$id_num2_typ02,$id_num2_typ03);
// print it on screen
echo '<pre>id_num2:<br />';
print_r($appln_idNum2);
echo '</pre>';
} // this closes the above foreach, i.e. the code will loop to every value of the first array
As result I receive for example following data:
id_num2:
Array
(
[0] => 41558194
[1] => 44677841
[2] => 44503689
[3] => 40651770
[4] => 41667291
)
id_num2:
Array
(
[0] => 15458354
[1] => 35477154
[2] => 15703123
[3] => 95151111
[4] => 55567125
)
etc.
In our case we will have 10 small arrays like that.
My problem is: How can I merge this small arrays so in the ende I have only one array?
Thank you for your help to solve this particular problem. Maybe is there also another possibility to write the code to be better and more efficient.

Breaking an array into groups based on values

Using PHP, I'm trying to break an array up into multiple arrays based on groups of values. The groups are based on the values being between 1 and 5. But here's the hard part...
I need to loop through the array and put the first set of values that are between 1 and 5 in their own array, then the next set of values that are between 1 and 5 in their own array, and so on.
But each group WON'T always include 1,2,3,4,5. Some groups could be random.
Examples:
1,1,2,2,3,4,5 - this would be a group
1,2,3,4,4,4 - this would be a group
1,2,3,3,5 - this would be a group
2,2,3,3,5 - this would be a group
So I can't just test for specific numbers.
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 1
[6] => 2
[7] => 3
[8] => 4
[9] => 4
[10] => 1
[11] => 1
[12] => 3
[13] => 4
[14] => 5
)
Any Ideas?
I would just check if the current value is larger than the previous value, and if yes, begin a new group.
$groups = array();
$groupcount = 1;
foreach( $array as $key=>$value )
{
if( $key > 0 ) // there's no "previous value" for the first entry
{
if( $array[$key] < $array[$key-1] )
{
$groupcount = $groupcount + 1;
}
}
$group[groupcount][] = $value;
}
Is this what you are looking for?
$groups = array();
$cur = array();
$prev = 0;
foreach ($numbers as $number)
{
if ($number < $prev)
{
$groups[] = $cur;
$cur = array();
}
$cur[] = $number;
$prev = $number;
}
if ($cur) $groups[] = $cur;
Untested. (Edit: corrected some obvious mistakes.)

Categories