如何在数组中的PHP中使用“两个”计数器?

时间:2019-04-08 15:57:41

标签: php

我得到2个数组,第一个是用户检查的id列表,第二个是用户ID,我想存储在数据库中

array(2) { 
    ["id_users"]=> string(6) "2,5,6," 
    ["selected"]=> string(30) "1,2,2,2,2,1,2,2,2,2,2,1,1,1,1," 
}

我应该将“ 1,2,2,2,2”存储到用户“ 2”,将“ 1,2,2,2,2”存储到用户“ 5”, 用户“ 6”的“ 2,1,1,1,1”

$list_checked = explode(",", $_GET['selected']);
//$class_name = explode(",", $_GET['class_name']);
$id_user = explode(",", $_GET['id_users']);
$count =  count($list_checked);
$count_id =  count($id_user);
$count_i = $count - 1;
$count_id_i = $count_id - 1;
$n = $count_i / $count_id_i ;

1 个答案:

答案 0 :(得分:0)

以下是一些适合您的代码:

// NOTE, I removed last commas from strings in order to work correctly
$list_checked = explode(",", '1,2,2,2,2,1,2,2,2,2,2,1,1,1,1');
$id_user = explode(",", '2,5,6');
$count =  count($list_checked);
$count_id =  count($id_user);

// define chunk size as result of division
$chunk_size = $count / $count_id;

// get chunks
$chunks = array_chunk($list_checked, $chunk_size);

// ierate over user and get related chunk by key    
foreach ($id_user as $key => $value) {
    echo 'ID: ', $value, ', chunk: ', print_r($chunks[$key], 1);
}