PHP将一个数组循环到另一个数组中
我正在尝试将一个数组循环到另一个数组中,然后在某个约会网站的内部数组结束时重置该数组 我有一个从数据库查询填充的数组。这是我非常熟悉的,如下所示:PHP将一个数组循环到另一个数组中,php,arrays,Php,Arrays,我正在尝试将一个数组循环到另一个数组中,然后在某个约会网站的内部数组结束时重置该数组 我有一个从数据库查询填充的数组。这是我非常熟悉的,如下所示: $sql="SELECT users from users LIMIT 100;"; $pds=$database->pdo->prepare($sql); $pds->execute(array()); $rows=$pds->fetchAll(); 然后我需要用数据填充另一个数组,我尝试了两个想法: 一, 二, 最后,我
$sql="SELECT users from users LIMIT 100;";
$pds=$database->pdo->prepare($sql); $pds->execute(array()); $rows=$pds->fetchAll();
然后我需要用数据填充另一个数组,我尝试了两个想法:
一,
二,
最后,我需要在第一个数组中循环第二个数组,然后在第二个数组完成后重置/重新启动它
$num = 0;
foreach($rows as $value) {
$message = ucfirst($value['users'];
echo $message;
echo $accountArray[$num++]['1'];
}
对不起,如果这是一个小褶边
我试图得到一个解决方案,在这个解决方案中,我可以循环使用DB返回,然后继续循环使用内部$accountArray[](它没有外部$rows数组长)
我还想知道如何最好地归档$accountArray[],因为我认为我的语法很有启发性
谢谢
Adam首先,启动
$accountArray
就足够了。也许它可以根据数组的内容进行改进,但是根据您提供的数据,初始化是非常好的
关于两个数组的循环:最简单的事情是在这个数组上使用模(如果你把运算的两边分开,模的结果就是余数)。由于查询结果数组的键是连续的,我们可以使用以下方法:
<?php
$sql = "SELECT users from users LIMIT 100;";
$pds = $database->pdo->prepare($sql);
$pds->execute(array());
$rows = $pds->fetchAll();
$accountArray = array(
array(
'1' => '0',
'2' => 'data',
'3' => 'data',
'4' => 'data',
),
array(
'1' => '1',
'2' => 'data',
'3' => 'data',
'4' => 'data',
),
array(
'1' => '2',
'2' => 'data',
'3' => 'data',
'4' => 'data',
),
);
$accountCount = count($accountArray); // do this outside of the loop for performance
foreach($rows as $key => $row) {
$marker = $key % $accountCount; // the actual magic for selecting the correct array-index
$message = ucfirst($row['users']);
echo $message;
echo $accountArray[$marker]['1']; // do what you want with the result
}
您可以在foreach上使用一段时间,然后打破它,直到它满足您需要的数量,您为什么要这样做?
$num = 0;
foreach($rows as $value) {
$message = ucfirst($value['users'];
echo $message;
echo $accountArray[$num++]['1'];
}
<?php
$sql = "SELECT users from users LIMIT 100;";
$pds = $database->pdo->prepare($sql);
$pds->execute(array());
$rows = $pds->fetchAll();
$accountArray = array(
array(
'1' => '0',
'2' => 'data',
'3' => 'data',
'4' => 'data',
),
array(
'1' => '1',
'2' => 'data',
'3' => 'data',
'4' => 'data',
),
array(
'1' => '2',
'2' => 'data',
'3' => 'data',
'4' => 'data',
),
);
$accountCount = count($accountArray); // do this outside of the loop for performance
foreach($rows as $key => $row) {
$marker = $key % $accountCount; // the actual magic for selecting the correct array-index
$message = ucfirst($row['users']);
echo $message;
echo $accountArray[$marker]['1']; // do what you want with the result
}