将SQL查询输出为数组

时间:2014-04-19 20:00:28

标签: sql arrays wordpress

我正在使用以下内容从WordPress数据库中的表中检索记录....

global $wpdb;
echo '<table>';
$sellers = get_users('blog_id=1&orderby=nicename&role=sellers');
foreach ($sellers as $seller) 
    {
    echo '<tr>';
    echo '<td>' . $seller->user_login . '</td>';

    $count1 = $wpdb->get_results("SELECT COUNT(*) AS count FROM wp_mymeta2 a JOIN wp_mymeta1 b ON b.id = a.my_id WHERE a.value = '$seller->user_login' AND b.date_posted LIKE '%2014-04-19%'" );
    echo '<td>' . $count1[0]->count . '</td>'; 

    $count2 = $wpdb->get_results("SELECT COUNT(*) AS count FROM wp_mymeta2 a JOIN wp_mymeta1 b ON b.id = a.my_id WHERE a.value = '$seller->user_login' AND b.date_posted LIKE '%$2014-04-18%'" );
    echo '<td>' . $count2[0]->count . '</td>';

    $count3 = $wpdb->get_results("SELECT COUNT(*) AS count FROM wp_mymeta2 a JOIN wp_mymeta1 b ON b.id = a.my_id WHERE a.value = '$seller->user_login' AND b.date_posted LIKE '%2014-05-17%'" );
    echo '<td>' . $count3[0]->count . '</td>'; 

    echo '</tr>';
    }
echo '</table>';

这很有用,它返回我想要的数据并将其回显到表中。

我现在想把数据放到一个数组中,所以我最终得到......

var $example_data = array(
            array(
                'seller'    => '$seller',
            'date'      => '$date1',
                'count'     => '$count_result',
            ),
        array(
                'seller'    => '$seller',
            'date'      => '$date2',
                'count'     => '$count_result',
            ),
        array(
                'seller'    => '$seller',
            'date'      => '$date3',
                'count'     => '$count_result',
            ),
        );

有没有人有一个例子可以指出我在正确的方向上取得了类似的成就?

1 个答案:

答案 0 :(得分:4)

您可以在foreach循环中使用array_push函数

global $wpdb;
echo '<table>';
$sellers = get_users('blog_id=1&orderby=nicename&role=sellers');
$arrSellers = array();

foreach ($sellers as $seller) 
{
echo '<tr>';
echo '<td>' . $seller->user_login . '</td>';

$count1 = $wpdb->get_results("SELECT COUNT(*) AS count FROM wp_mymeta2 a JOIN wp_mymeta1 b ON b.id = a.my_id WHERE a.value = '$seller->user_login' AND b.date_posted LIKE '%2014-04-19%'" );
echo '<td>' . $count1[0]->count . '</td>'; 

$count2 = $wpdb->get_results("SELECT COUNT(*) AS count FROM wp_mymeta2 a JOIN wp_mymeta1 b ON b.id = a.my_id WHERE a.value = '$seller->user_login' AND b.date_posted LIKE '%$2014-04-18%'" );
echo '<td>' . $count2[0]->count . '</td>';

$count3 = $wpdb->get_results("SELECT COUNT(*) AS count FROM wp_mymeta2 a JOIN wp_mymeta1 b ON b.id = a.my_id WHERE a.value = '$seller->user_login' AND b.date_posted LIKE '%2014-05-17%'" );
echo '<td>' . $count3[0]->count . '</td>'; 

echo '</tr>';

 //add whatever you want to $arrSellers using array_push

}
echo '</table>';