array_splice函数使用方法已知数组res:array (SU13080800340 array (0 CVT121015001,1 CVT12
array_splice函数使用方法
已知数组res:
array (
'SU13080800340' =>
array (
0 => 'CVT121015001',
1 => 'CVT121015002',
2 => 'CVT121226001',
),
)
现有代码:
$sql = "SELECT stock_no, cust_no, mount FROM `stock_detail` where stock_no = 'value' ORDER BY arr_time, adress, c_type ASC";
//echo $sql;
$result = mysql_query($sql);
$str_arr = array();
while($v2 = mysql_fetch_array($result,MYSQL_ASSOC)) {
$v2[] = array_splice($res[$v2['stock_no']], 0, 1); //取出数组的前n项
var_export($v2);
}
得到的是数组v2:
array (
'stock_no' => 'SU13080800340',
'cust_no' => '310F61VA5A',
'mount' => '1',
0 =>
array (
0 => 'CVT121015001',
),
)array (
'stock_no' => 'SU13080800340',
'cust_no' => '310F61VA5A',
'mount' => '2',
0 =>
array (
0 => 'CVT121015002',
),
)
为什么不是这样的结果?
array (
'stock_no' => 'SU13080800340',
'cust_no' => '310F61VA5A',
'mount' => '1',
0 =>
array (
0 => 'CVT121015001',
),
)array (
'stock_no' => 'SU13080800340',
'cust_no' => '310F61VA5A',
'mount' => '2',
0 =>
array (
0 => 'CVT121015002',
1 => 'CVT121016001',
),
)
------解决方案--------------------
$res = array();
while($v2 = mysql_fetch_array($result,MYSQL_ASSOC)) {
$res[] = array_splice($res[$v2['stock_no']], 0, 1); //取出数组的前n项
}
var_export($res);
[解决办法]array_splice($res[$v2['stock_no']], 0, 1)
的作用是从 $res[$v2['stock_no']] 的第 0 个位置开始,删去 1 个元素,返回被删除的元素
当你的循环结束后 $res[$v2['stock_no']] 是这样的
array (
'SU13080800340' =>
array (
0 => 'CVT121226001',
),
)