search

Home  >  Q&A  >  body text

php array transformation

php array is as follows

array(6) {
  [17]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  [11]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [10]=>
  array(1) {
    [0]=>
    string(1) "6"
  }
  [9]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
}

How does the above array become the following one?

[['17','1'],['11','2'],['10','6'],['9','1']]
谢谢大神
習慣沉默習慣沉默2766 days ago1035

reply all(4)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-06-12 09:24:11

    <?php
    $arrayOld = array(
        '17' => array('1'),
        '11' => array('2'),
        '10' => array('6'),
        '9' => array('1'),
    );
    $arrayNew = [];
    
    foreach($arrayOld as $key => $value){
        $arrayNew[] = [(string)$key,$value[0]];
    }
    
    var_export ($arrayNew);

    reply
    0
  • 習慣沉默

    習慣沉默2017-06-12 09:24:11

    $old = array(
        '17' => '1',
        '11' => '2',
        '10' => '6',
        '9' => 1 
    );
    
    $new = array_chunk($old, 1, true);
    foreach ($new as $key => &$val) {
        array_unshift($val, $key);
    }
    var_dump($new);

    reply
    0
  • 为情所困

    为情所困2017-06-12 09:24:11

    <?php
    
      $data= array(
        '17' => array('1'),
        '11' => array('2'),
        '10' => array('6'),
        '9' => array('1'),
      );
    
      function maps(&$array,$key) {
        array_unshift($array, $key);
      }
    
      array_walk($data, 'maps');
      print_r($data);
    ?>

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-06-12 09:24:11

    The answers given by the respondents above are all quite good, and I can’t help but express my ugliness

    $old = [
      '17' => ['1'],
      '11' => ['2'],
      '10' => ['6'],
      '9' => ['1'],
    ];
    $new = [];
    foreach ($old as $key => $value) {
      $new[] = [$key, $value[0]];
    }
    var_dump($new);

    It’s actually quite simple. The answer won’t be much different, so I’ll simply add some explanations

    First of all, you need to learn to traverse foreach, and then PHP is a weakly typed language, and the variable type is converted by itself

    Oh yes, the other thing you need to know is $arr[] = $var, which is like adding elements to the end of an array. Another method is array_push($arr, $var), but this method is less efficient than the first one

    reply
    0
  • Cancelreply