【问题标题】:How to correctly populate Array from While Loop PHP如何从 While 循环 PHP 中正确填充数组
【发布时间】:2016-06-26 18:13:15
【问题描述】:

我正在从 While 循环填充一个数组,但无法生成正确的数组格式。我遇到了许多不同的变化,但不是我正在寻找的,包括在下面。目的是用于第 3 方 SMTP,如变量 $to 中所示

所需的数组:

array(3) { 
    ["email1@email1.com"]=> array(1) { ["userid"]=> string(1) "6" } 
    ["email2@email2.com"]=> array(1) { ["userid"]=> string(2) "64" } 
    ["email3@email3.com"]=> array(1) { ["userid"]=> string(3) "503" } 
}

尝试 1:

$str = array();
while($userEmails = $query->fetch(PDO::FETCH_ASSOC)){

    $str[] = '"'.$userEmails['user_email'].'"  => array( 
       "userid" => "'.$userEmails['user_id'].'" 
    )';
}
$to = $str;

尝试 1 不正确的数组:

array(3) {
     [0]=> string(54) ""email1@email1.com" => array( "userid" => "6" )"       
     [1]=> string(54) ""email2@email2.com" => array( "userid" => "64" )" 
     [2]=> string(54) ""email3@email3.com" => array( "userid" => "503" )" 
}

尝试 2:

$str = "";
while($userEmails = $query->fetch(PDO::FETCH_ASSOC)){

    $str .= '"'.$userEmails['user_email'].'"  => array( "userid" => "'.$userEmails['user_id'].'" )';
}

$emails = rtrim($str, ", ");

$to = array($emails);

尝试 2 不正确的数组:

array(1) { 
    [0]=> string(162) ""email1@email1.com" => array( "userid" => "6" )"email2@email2.com" => array( "userid" => "64" )"email3@email3.com" => array( "userid" => "503" )" }

【问题讨论】:

  • imo,如果您最初将其作为单独的步骤进行操作会更容易理解吗? 1)$userEmail = $userEmails['user_email']; 2)$userId = $userEmails['user_id'];。从这里有很多方法可以做到这一点...... 3)(一种方式:)$str[][$userEmail]['userid'] = $userid;

标签: php arrays variables while-loop


【解决方案1】:

你想要这个,我想:

$str = array();
while($userEmails = $query->fetch(PDO::FETCH_ASSOC)){
    $str[$userEmails['user_email']] = array(
        'user_id' => $userEmails['user_id']
    );
}

【讨论】:

    【解决方案2】:

    我个人认为将whilefetch 一起使用会迫使您接受丑陋的代码。我通常有几个实用函数来编写更多的声明性代码

    function query_reduce(callable $f, $initialValue, $query) {
      $result = $initialValue;
      while($x = $query->fetch(PDO::FETCH_ASSOC))
        $z = call_user_func($f, $x);
      return $result;
    }
    

    现在你可以写这个了

    $result = query_reduce(function ($acc, $x) {
      $acc[$x['user_email']] = [['user_id'] => $x['user_id']];
      return $acc;
    }, [], $query);
    
    var_dump($result);
    

    query_reduce 只是我使用的助手之一。这是一个类似于foreach

    // use like foreach
    function query_foreach(callable $f, $query) {
      query_reduce(function($i, $x) {
        call_user_func($f, $i++);
      }, 0, $query);
    }
    
    // $query returns [{id:'a'}, {id:'b'}, {id:'c'}]
    query_foreach(function ($x, $i) {
      echo "{$x['id']} is in position {$i}";
    });
    
    // output
    // a is in position 0
    // b is in position 1
    // c is in position 2
    

    或用于映射查询的一种

    // use like array_map
    function query_map(callable $f, $query) {
      $i = 0;
      return query_reduce(function ($acc, $x) use ($i) {
        return array_merge($acc, [call_user_func($f, $x, $i++)]);
      }, [], $query);
    }
    
    // $query returns [{id:'a'}, {id:'b'}, {id:'c'}]
    $ids = query_foreach(function ($x, $i) {
      return ['id'=> $x['id'], 'position'=> $i];
    });
    
    print_r($ids);
    
    // output...
    // Array
    // (
    //     Array
    //     (
    //         [id] => a
    //         [position] => 0
    //     )
    //     Array
    //     (
    //         [id] => b
    //         [position] => 1
    //     )
    //     Array
    //     (
    //         [id] => c
    //         [position] => 2
    //     )
    // )
    

    【讨论】:

    • 这很棒。感谢分享
    • @Klav 很高兴你喜欢它。一旦你抽象出所有冗长的 while 代码,最终结果看起来相当不错。
    • 完全。玩这些真是太棒了
    【解决方案3】:

    试试这个方法:

    $str = array();
    while($userEmails = $query->fetch(PDO::FETCH_ASSOC)){
        $str[$userEmails['user_email']] = array('userid' => $userEmails['user_id']);
    }
    
    $to = $str;
    

    【讨论】:

    • 这正是我 5 分钟前发布的内容。
    猜你喜欢
    • 2011-10-08
    • 1970-01-01
    • 2012-05-30
    • 2013-11-03
    • 2015-04-30
    • 2017-07-15
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    相关资源
    最近更新 更多