开发者

Php Loop with a List

开发者 https://www.devze.com 2023-02-11 05:46 出处:网络
I have a PHP code like that: $cityCount=10; $currentUsers = array(); $ad开发者_JS百科dedUsers = array();

I have a PHP code like that:

$cityCount=10;
$currentUsers = array();
$ad开发者_JS百科dedUsers = 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

0

精彩评论

暂无评论...
验证码 换一张
取 消