Php-在多维数组中重置初始id
我这里有一个数组:Php-在多维数组中重置初始id,php,arrays,Php,Arrays,我这里有一个数组: Array ( [1] => Array ( [id] => 1 [items] => Array ( [0] => Array ( [id] => 1
Array
(
[1] => Array
(
[id] => 1
[items] => Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 2
)
[2] => Array
(
[id] => 3
)
)
)
[2] => Array
(
[id] => 2
[items] => Array
(
[0] => Array
(
[id] => 4
)
[1] => Array
(
[id] => 5
)
)
)
)
问题:当项目“id
转到第二个数组时,如何重置该项目?
我一直在绞尽脑汁想一个算法,但找不到一个方法:(
这是我如何获得数组的源代码(如果有帮助)。为了清晰起见,我简化了数组,下面的代码是扩展代码:
$results = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$i++;
$results[] = array(
$row['id'] => array(
'category' => $row['category'],
'items' => array(
array(
'id' => $i, //THIS IS THE PROBLEM
'name' => $row['name'],
'user_name' => $row['user_name'],
'price' => $row['price'],
'item_photo' => $row['item_photo'],
'item_description' => $row['item_description']
)
)
)
);
}
// Begin rebuilding trees
$output = array();
//$results is array from mysql
foreach ($results as $data) {
//var_dump($data);
//dumping each block of array
foreach ($data as $categoryId => $item) {
//check if NOT yet set
if (!isset($output[$categoryId])) {
//insert values in the first Array()
$output[$categoryId] = array(
'id' => $categoryId,
'category' => $item['category'],
'items' => array()
);
}
//populate 'items' array with stuff
$output[$categoryId]['items'] =
array_merge(
$output[$categoryId]['items'],
$item['items']
);
}
}
如果有任何问题,请告诉我。首先,也是最重要的一点,请不要使用mysql\u*
API,因为这些函数现在已被弃用。相反,请使用或(我个人会使用PDO,因为它支持各种数据库连接,但这只是我的意见)
要解决id
的问题,您只需将以前的id存储在变量中并对其进行测试。以下可能不正确,因为您的代码非常混乱,但它应该足以让您走上正确的道路:
$i = 0;
while($row = mysql_fetch_assoc($result)){
// Only increment i if it is still the same row
// otherwise reset it
if($row_id==$row['id']){
$i++;
}else{
$i = 0;
}
// Set the new row id
$row_id = $row['id'];
// Do your stuff...
}
假设您的结果已排序,因此每个类别的项目都是连续的(一个类别不会显示在结果的不同位置): 此外,您还可以将设置
$i
设置为一行:
// If the current category is different than the previous, reset $i
$i = $row['category'] != $oldCat ? 0 : $i++;
为了清楚起见,请注意,您可能需要创建更具描述性的数组键。例如,您有
id
两次-这可能是category\u id
和item\u id我的意思是,我想在第一个数组之后将键[id]
重置为1。该键位于[items]中
array。谢谢,我稍后会考虑键的问题。较长的解决方案有效。但是,您的单行解决方案将所有ID返回到0,即使我将$oldCat放在行的前面或后面。无论如何都可以。$oldCat=$row['category']
应该在一行程序之后立即执行。奇怪的是,它不起作用。很高兴较长的解决方案对您有效!谢谢您的解决方案也有效。无论如何,我计划稍后迁移到mysqli*
。谢谢提醒。
// If the current category is different than the previous, reset $i
$i = $row['category'] != $oldCat ? 0 : $i++;