Home  >  Article  >  Backend Development  >  php处理post的数组

php处理post的数组

WBOY
WBOYOriginal
2016-06-06 20:28:371819browse

第一组checkbox提交的数组如下
array('sort'=>array(0,2,3,1))
第二组checkbox提交的数组如下
array('id'=>array(1,2,3,4))
如何处理成下面我想要的数组结果
array(
array('sort'=>0,'id'=>1),
array('sort'=>2,'id'=>2),
array('sort'=>3,'id'=>3),
array('sort'=>1,'id'=>4),
)

回复内容:

第一组checkbox提交的数组如下
array('sort'=>array(0,2,3,1))
第二组checkbox提交的数组如下
array('id'=>array(1,2,3,4))
如何处理成下面我想要的数组结果
array(
array('sort'=>0,'id'=>1),
array('sort'=>2,'id'=>2),
array('sort'=>3,'id'=>3),
array('sort'=>1,'id'=>4),
)

<code class="php">$res = array_map(function($v1,$v2){
return ['sort'=>$v1,'id'=>$v2];
},$a['sort'],$b['id']);
/* [
       [
           "sort" => 0,
           "id"   => 1
       ],
       [
           "sort" => 2,
           "id"   => 2
       ],
       [
           "sort" => 3,
           "id"   => 3
       ],
       [
           "sort" => 1,
           "id"   => 4
       ]
   ]
*/</code>

上面回答的很好,用array_map的确是最好的方法了,不过语法在低版本上的不兼容,我写了一个完整的,可直接测试

<code><?php $a = array('sort'=>array(0,2,3,1));
    $b = array('id'=>array(1,2,3,4));
    
    $res = array_map(function($v1,$v2){ 
        return array('sort'=>$v1,'id'=>$v2);
    },$a['sort'],$b['id']);
    
    print_r($res);   </code>

结果

<code>Array
(
    [0] => Array
        (
            [sort] => 0
            [id] => 1
        )

    [1] => Array
        (
            [sort] => 2
            [id] => 2
        )

    [2] => Array
        (
            [sort] => 3
            [id] => 3
        )

    [3] => Array
        (
            [sort] => 1
            [id] => 4
        )

)</code>

<code><?php header('Content-Type: text/plain; charset=utf-8');
$arr1 = array('sort' => array(0,2,3,1));
$arr2 = array('id'   => array(1,2,3,4));
$arr = array_merge($arr1, $arr2);
$new = array();
foreach($arr as $k => $v) {
    foreach($v as $k1 => $v1) {
        $new[$k1][$k] = $v1;
    }
}
print_r($new);</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn