简体   繁体   English

从SQL结果中过滤大型数组

[英]Filtering large array from SQL result

I have an SQL query that returns 14 rows per userID. 我有一个SQL查询,每个用户ID返回14行。

It pulls a lot of data to verify different fields, but specifically returned I need the first and last name. 它提取了大量数据来验证不同的字段,但具体返回时,我需要名字和姓氏。 The first name I can get from $firstName[]=$row2[0]; 我可以从$firstName[]=$row2[0];获得的名字$firstName[]=$row2[0]; but I can't get the last name value out of the array. 但是我无法从数组中获取姓氏值。 I can see its position, but I'm not sure how to call that position in the loop. 我可以看到它的位置,但是我不确定如何在循环中调用该位置。

echo '<table border=1><tr><td>Student ID</td><td>Full Name</td><td>Class</td></tr>';


    //Build Student Info1 table
    foreach($userID as $val) {
    $user_id= $val;
    $query="SELECT * FROM wp_usermeta WHERE meta_key ='purchased_instances' AND user_id ='$user_id'";
    $query2="SELECT meta_value FROM wp_usermeta WHERE user_id ='$user_id'";

    $result = $link->query($query)or die($link->error);
    $result2 = $link->query($query2)or die($link->error);



    if($result->num_rows > 0){
    /* fetch associative array */

         $i=0;
         while ($row = mysqli_fetch_array($result)) {
             while($row2 = mysqli_fetch_array($result2)) {

                $details[$i][]=$row2;
                $firstName[]=$row2[0];
                $lastName[]=$row2[0];  //Can't get this value right, need the first element of the 2 indexed array 

             }

            $result1[]=$row;
            $studentID[$i]=$row[1];
            $classDetails[$i]=$row[3];

            echo'<tr><td>';
            print_r($studentID[$i]);
            echo '</td><td>';
            print_r($firstName[$i]);
            echo ' ';
            print_r($lastName[$i]);
            echo'</td><td>';
            print_r($classDetails[$i]);
            echo '</td></tr>';


            $i++;
        }
/* free result set */
mysqli_free_result($result);
}
}
echo '</table>';

This is what print_r($details) produces: 这是print_r($details)产生的结果:

Array ( [0] => Array ( [0] => 2567 [umeta_id] => 2567 [1] => 185 [user_id] => 185 [2] => first_name [meta_key] => first_name [3] => Kevin [meta_value] => Kevin ) [1] => Array ( [0] => 2568 [umeta_id] => 2568 [1] => 185 [user_id] => 185 [2] => last_name [meta_key] => last_name [3] => RealLastNameHERE [meta_value] => RealLastNameHERE ) [2] => Array ( [0] => 2569 [umeta_id] => 2569 [1] => 185 [user_id] => 185 [2] => nickname [meta_key] => nickname [3] => KMOwner [meta_value] => KMOwner ) [3] => Array ( [0] => 2570 [umeta_id] => 2570 [1] => 185 [user_id] => 185 [2] => description [meta_key] => description [3] => [meta_value] => ) [4] => Array ( [0] => 2571 [umeta_id] => 2571 [1] => 185 [user_id] => 185 [2] => rich_editing [meta_key] => rich_editing [3] => true [meta_value] => true ) [5] => Array ( [0] => 2572 [umeta_id] => 2572 [1] => 185 [user_id] => 185 [2] => comment_shortcuts [meta_key] => comment_shortcuts [3] => false [meta_value] => false ) [6] => Array ( [0] => 2573 [umeta_id] => 2573 [1] => 185 [user_id] => 185 [2] => admin_color [meta_key] => admin_color [3] => fresh [meta_value] => fresh ) [7] => Array ( [0] => 2574 [umeta_id] => 2574 [1] => 185 [user_id] => 185 [2] => use_ssl [meta_key] => use_ssl [3] => 0 [meta_value] => 0 ) [8] => Array ( [0] => 2575 [umeta_id] => 2575 [1] => 185 [user_id] => 185 [2] => show_admin_bar_front [meta_key] => show_admin_bar_front [3] => true [meta_value] => true ) [9] => Array ( [0] => 2576 [umeta_id] => 2576 [1] => 185 [user_id] => 185 [2] => wp_capabilities [meta_key] => wp_capabilities [3] => a:1:{s:10:"subscriber";b:1;} [meta_value] => a:1:{s:10:"subscriber";b:1;} ) [10] => Array ( [0] => 2577 [umeta_id] => 2577 [1] => 185 [user_id] => 185 [2] => wp_user_level [meta_key] => wp_user_level [3] => 0 [meta_value] => 0 ) [11] => Array ( [0] => 2578 [umeta_id] => 2578 [1] => 185 [user_id] => 185 [2] => mgm_member_options [meta_key] => mgm_member_options [3] => a:35:{s:2:"id";i:185;s:13:"custom_fields";a:6:{s:10:"first_name";s:5:"Kevin";s:9:"last_name";s:13:"RealLastNameHERE";s:5:"email";s:23:"RealEmailAddressHERE";s:8:"username";s:7:"RealuserNameHERE";s:8:"password";s:16:"Lwp9E8RZECyB9bzb";s:13:"password_conf";N;}s:22:"other_membership_types";a:0:{}s:12:"payment_info";a:0:{}s:6:"coupon";a:2:{s:12:"update_usage";b:0;s:15:"coupon_usage_id";b:0;}s:7:"upgrade";a:1:{s:6:"coupon";a:0:{}}s:6:"extend";a:0:{}s:4:"code";s:10:"mgm_member";s:4:"name";s:10:"Member Lib";s:11:"description";s:10:"Member Lib";s:7:"setting";a:0:{}s:6:"saving";b:1;s:8:"trial_on";i:0;s:10:"trial_cost";d:0;s:14:"trial_duration";i:0;s:19:"trial_duration_type";s:1:"d";s:16:"trial_num_cycles";i:0;s:8:"duration";i:1;s:13:"duration_type";s:1:"l";s:6:"amount";d:0;s:8:"currency";s:3:"USD";s:9:"join_date";i:1383183050;s:13:"last_pay_date";s:0:"";s:11:"expire_date";s:0:"";s:15:"membership_type";s:4:"free";s:6:"status";s:6:"Active";s:12:"payment_type";s:0:"";s:13:"autoresponder";s:10:"mgm_aweber";s:10:"subscribed";s:1:"Y";s:22:"autoresponder_notified";s:1:"Y";s:13:"user_password";s:16:"Lwp9E8RZECyB9bzb";s:17:"active_num_cycles";i:1;s:7:"pack_id";s:2:"22";s:12:"account_desc";s:12:"Free Account";s:16:"hide_old_content";s:1:"0";} [meta_value] => a:35:{s:2:"id";i:185;s:13:"custom_fields";a:6:{s:10:"first_name";s:5:"Kevin";s:9:"last_name";s:13:"RealLastNameHERE";s:5:"email";s:23:"RealuserNameHERE";s:8:"username";s:7:"RealuserNameHERE";s:8:"password";s:16:"Lwp9E8RZECyB9bzb";s:13:"password_conf";N;}s:22:"other_membership_types";a:0:{}s:12:"payment_info";a:0:{}s:6:"coupon";a:2:{s:12:"update_usage";b:0;s:15:"coupon_usage_id";b:0;}s:7:"upgrade";a:1:{s:6:"coupon";a:0:{}}s:6:"extend";a:0:{}s:4:"code";s:10:"mgm_member";s:4:"name";s:10:"Member Lib";s:11:"description";s:10:"Member Lib";s:7:"setting";a:0:{}s:6:"saving";b:1;s:8:"trial_on";i:0;s:10:"trial_cost";d:0;s:14:"trial_duration";i:0;s:19:"trial_duration_type";s:1:"d";s:16:"trial_num_cycles";i:0;s:8:"duration";i:1;s:13:"duration_type";s:1:"l";s:6:"amount";d:0;s:8:"currency";s:3:"USD";s:9:"join_date";i:1383183050;s:13:"last_pay_date";s:0:"";s:11:"expire_date";s:0:"";s:15:"membership_type";s:4:"free";s:6:"status";s:6:"Active";s:12:"payment_type";s:0:"";s:13:"autoresponder";s:10:"mgm_aweber";s:10:"subscribed";s:1:"Y";s:22:"autoresponder_notified";s:1:"Y";s:13:"user_password";s:16:"Lwp9E8RZECyB9bzb";s:17:"active_num_cycles";i:1;s:7:"pack_id";s:2:"22";s:12:"account_desc";s:12:"Free Account";s:16:"hide_old_content";s:1:"0";} ) [12] => Array ( [0] => 2579 [umeta_id] => 2579 [1] => 185 [user_id] => 185 [2] => _wpsc_customer_profile [meta_key] => _wpsc_customer_profile [3] => a:5:{s:16:"shipping_country";s:2:"US";s:15:"billing_country";s:2:"US";s:15:"shipping_region";s:2:"22";s:14:"billing_region";s:2:"22";s:4:"cart";s:1056:"O:9:"wpsc_cart":37:{s:16:"delivery_country";s:2:"US";s:16:"selected_country";s:2:"US";s:15:"delivery_region";s:2:"22";s:15:"selected_region";s:2:"22";s:24:"selected_shipping_method";N;s:24:"selected_shipping_option";N;s:24:"selected_shipping_amount";N;s:6:"coupon";N;s:14:"tax_percentage";N;s:9:"unique_id";s:40:"905310a45d51d75129b9de961ae17f69a7129ced";s:6:"errors";a:0:{}s:9:"total_tax";N;s:13:"base_shipping";N;s:19:"total_item_shipping";N;s:14:"total_shipping";N;s:8:"subtotal";N;s:11:"total_price";N;s:13:"uses_shipping";N;s:13:"is_incomplete";b:1;s:10:"cart_items";a:0:{}s:9:"cart_item";N;s:15:"cart_item_count";i:0;s:17:"current_cart_item";i:-1;s:11:"in_the_loop";b:0;s:16:"shipping_methods";b:0;s:15:"shipping_method";N;s:21:"shipping_method_count";i:1;s:23:"current_shipping_method";i:-1;s:18:"in_the_method_loop";b:0;s:15:"shipping_quotes";a:0:{}s:14:"shipping_quote";N;s:20:"shipping_quote_count";i:0;s:22:"current_shipping_quote";i:-1;s:17:"in_the_quote_loop";b:0;s:12:"coupons_name";s:0:"";s:14:"coupons_amount";i:0;s:15:"shipping_option";N;}";} [meta_value] => a:5:{s:16:"shipping_country";s:2:"US";s:15:"billing_country";s:2:"US";s:15:"shipping_region";s:2:"22";s:14:"billing_region";s:2:"22";s:4:"cart";s:1056:"O:9:"wpsc_cart":37:{s:16:"delivery_country";s:2:"US";s:16:"selected_country";s:2:"US";s:15:"delivery_region";s:2:"22";s:15:"selected_region";s:2:"22";s:24:"selected_shipping_method";N;s:24:"selected_shipping_option";N;s:24:"selected_shipping_amount";N;s:6:"coupon";N;s:14:"tax_percentage";N;s:9:"unique_id";s:40:"905310a45d51d75129b9de961ae17f69a7129ced";s:6:"errors";a:0:{}s:9:"total_tax";N;s:13:"base_shipping";N;s:19:"total_item_shipping";N;s:14:"total_shipping";N;s:8:"subtotal";N;s:11:"total_price";N;s:13:"uses_shipping";N;s:13:"is_incomplete";b:1;s:10:"cart_items";a:0:{}s:9:"cart_item";N;s:15:"cart_item_count";i:0;s:17:"current_cart_item";i:-1;s:11:"in_the_loop";b:0;s:16:"shipping_methods";b:0;s:15:"shipping_method";N;s:21:"shipping_method_count";i:1;s:23:"current_shipping_method";i:-1;s:18:"in_the_method_loop";b:0;s:15:"shipping_quotes";a:0:{}s:14:"shipping_quote";N;s:20:"shipping_quote_count";i:0;s:22:"current_shipping_quote";i:-1;s:17:"in_the_quote_loop";b:0;s:12:"coupons_name";s:0:"";s:14:"coupons_amount";i:0;s:15:"shipping_option";N;}";} ) [13] => Array ( [0] => 2580 [umeta_id] => 2580 [1] => 185 [user_id] => 185 [2] => purchased_instances [meta_key] => purchased_instances [3] => Cardio Stretch/Flex on 11/04/2013 8:00 AM [meta_value] => Cardio Stretch/Flex on 11/04/2013 8:00 AM )

============================================================================== ================================================== ============================

New working code: 新的工作代码:

    echo '<table border=1><tr><td>Full Name</td><td>Class Purchased</td></tr>';


    //Build Student Info1 table
    foreach($userID as $val) {
    $user_id= $val;
    $queryA="SELECT meta_value FROM wp_usermeta WHERE meta_key ='first_name' AND user_id ='$user_id'";
    $queryB="SELECT meta_value FROM wp_usermeta WHERE meta_key ='last_name' AND user_id ='$user_id'";
    $queryC="SELECT meta_value FROM wp_usermeta WHERE meta_key ='purchased_instances' AND user_id ='$user_id'";

    $resultA = $link->query($queryA)or die($link->error);
    $resultB = $link->query($queryB)or die($link->error);
    $resultC = $link->query($queryC)or die($link->error);

    $numPurchases = $resultC->num_rows;

    if($numPurchases > 0){

        $i=0;
        foreach($resultA as $val){

                $fName[$i]=$val['meta_value'];;
                $i++;
        }

        $i=0;
        foreach($resultB as $val){

                $lName[$i]=$val['meta_value'];  
                $i++;

        }

        $i=0;
        foreach($resultC as $val){

                $classDetails[$i]=$val['meta_value'];   
                $i++;

        }

        for($i=0; $i < $numPurchases; $i++){
        echo '<td>';
        print_r($fName[$i]);
        echo ' ';
        print_r($lName[$i]);
        echo '</td><td>';
        print_r($classDetails[$i]);
        echo '</td></tr>';  


        }

/* free result set */
mysqli_free_result($resultA);
mysqli_free_result($resultB);
mysqli_free_result($resultC);
}

} echo ''; }回声'';

Some important notes: 一些重要的注意事项:

  • Validate any user input 验证任何用户输入
  • NEVER execute SQL in a loop 永远不要在循环中执行SQL
  • Use one query that fetches everything you need (you're using the same table) 使用一个查询来获取您需要的所有内容(您使用的是同一张表)
  • Fetch an associative array, this will help you a lot 获取关联数组,这将对您有很大帮助
  • Specify exactly what you need in your projection (not * after SELECT , exactly state each field to fetch like SELECT foo , bar , … ) 确切指定投影中需要的内容(在SELECT之后不要* ,要准确说明要提取的每个字段,例如SELECT foo , bar , …

Here is some code to help you get started with the above tips: 以下是一些代码,可帮助您开始使用上述提示:

<?php

// Validate input, please note that prepared statements would be best.
// Also note that we don't need mysql escape calls because we validate
// that this is an actual integer value which can't contain anything
// dangerous. If we'd be working with any kind of string, date, ... the
// world would look different.
if (!is_array($userID)) {
  if (!is_int($userID)) {
    throw new \RuntimeException;
  }
  $userIds = "= {$userID}";
}
else {
  $userIds = null;
  $c       = count($userID);
  for ($i = 0; $i < $c; ++$i) {
    if (!is_int($userID[$i])) {
      throw new \RuntimeException;
    }
    $userIds .= $userIds ? "," : "IN(";
    $userIds .= $userID[$i];
  }
  $userIds .= ")";
}

// One query to rule them all and nice formatting for readability.
$result = $link->query(
  "SELECT *
  FROM `wp_usermeta`
  WHERE `meta_key` = 'purchased_instances'
    AND `user_id` {$userIds}"
);

// Now we fetch everything within a single loop.
while ($row = mysqli_fetch_assoc($result)) {
  print_r($row);
}

// That's it!
mysqli_free_result($result);

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM