donglu5728 2018-01-20 23:50
浏览 190
已采纳

PHP数据库循环遍历数组以查找id,然后使用id显示该列的值

Currently I have been able to find the correct table and print_r the content of the array. Now I'm trying to loop through that array and display usernames and points from that array based on the id. This is what the array looks like

Array
(
[0] => stdClass Object
(
[id] => 5a61d2f40394d
[first] => Test
[last] => Guy3
[company] => 123 Company
[points] => 50
[url] => https://example.com/points/?user=5a61d2f40394d
[created] => 0000-00-00 00:00:00
[updated] => 2018-01-19 06:22:42
)

[1] => stdClass Object
(
[id] => 5a61cdddc359d
[first] => Test
[last] => Guy1
[company] => 123 Company
[points] => 0
[url] => https://example.com/points/?user=5a61cdddc359d
[created] => 0000-00-00 00:00:00
[updated] => 2018-01-19 05:52:13
)

[2] => stdClass Object
(
[id] => 5a61d054a0915
[first] => Test
[last] => Guy2
[company] => 123 Company
[points] => 0
[url] => https://example.com/points/?user=5a61d054a0915
[created] => 0000-00-00 00:00:00
[updated] => 2018-01-19 06:02:44
)

)

This is what I've written so far and I've been able to find the id but now I want to access the points and update them after..

global $wpdb; //this is wordpress so I'm accessing the database
//here I'm reading the variable ?user= in the url
$queryURL = parse_url( html_entity_decode( esc_url( add_query_arg( $arr_params ) ) ) );
parse_str( $queryURL['query'], $getVar );
$user = $getVar['user'];

$customers = $wpdb->get_results("SELECT * FROM `wpjw_skmember`;");
//I've found the users id but now I need to update their points but I don't know how.
$first = array_column($customers, 'id');

foreach($first as $value) {
   if  ($value == $user) {
       echo 'user found'
   }    
}
  • 写回答

1条回答 默认 最新

  • douou9094747 2018-01-21 00:08
    关注

    If your $customers array is of the format posted above, then accessing values within it would work like this:

    echo $customers[0]->last; // returns "Guy3"
    

    So, you could loop over $customers and test each customer within that array to see if the ID value matches, then access the other values when it does:

    foreach ($customers as $customer){
        if ($customer->id == $user){
            echo $customer->last . " has " . $customer->points . " points!";
            break;
        }
    }
    

    Using break after identifying the matching user will exit from the foreach loop, preventing additional needless iterations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?