在这种情况下,如何转换数组数据来使用它?尤其是在wordpress中。当我打印结果时,我得到了stdClass对象。
Array
(
[0] => stdClass Object
(
[posts_id] => 336
[value] => 8
[count(*)] => 2
)
[1] => stdClass Object
(
[posts_id] => 329
[value] => 2
[count(*)] => 1
)
[2] => stdClass Object
(
[posts_id] => 327
[value] => 3
[count(*)] => 1
)
[3] => stdClass Object
(
[posts_id] => 338
[value] => 1
[count(*)] => 1
)
)
这是我的查询
<?php global $wpdb;
$test = $wpdb->get_results('select
posts_id,
value,
count(*)
From
wp_mrp_rating_item_entry_value
group by
posts_id,
value
order by
count(*) desc');
echo '<pre>';
print_r($test);
echo '</pre>';
如何将此数组中的数据保存到另一个数据库表中?或者,我如何至少将单个值保存到每个id的变量中?我试过分配,但我还不知道,所以我希望有人比我更清楚?谢谢你的帮助。
foreach($test as $item) :
$ID = $item->posts_id;
var_dump($ID); //test variable
//if you want to place into the db
//DB CODE>>>
$firstName = "Dylan" //example of field in db to change
$LastName = "bloggs" //example of second field in db to change
$wpdb->query( $wpdb->prepare(
"
INSERT INTO $wpdb->name_of_wp_table_goes_here
( name_of_field_goes_here )
VALUES ( %d, %s, $s )
",
$ID,
$field
) );
//<<<DB END
endforeach;
如果要手动存储到数据库中,请删除数据库代码。
您也可以以相同的方式访问其他密钥。例如,$value=$item->value;--您将把它放在foreach循环中,然后继续。
在Wordpress中,当您使用get_results时,您可以选择脱水模式:
输出类型三个预定义常量之一。默认为OBJECT。OBJECT-结果将作为对象输出。ARRAY_A-结果将作为关联数组输出。ARRAY_N-结果将作为数字索引数组输出。
所以,如果你这样做:
$test = $wpdb->get_results('select
posts_id,
value,
count(*)
From
wp_mrp_rating_item_entry_value
group by
posts_id,
value
order by
count(*) desc', ARRAY_N);
您应该得到一个数组作为结果。
由于这是一个对象数组,您可以使用简单的foreach来访问您的值:
<?php
foreach ($test as $t) {
$t->post_id;
$t->value;
// You can insert your values in different table here
}
?>
对于计数,您可以将查询更改为:
SELECT posts_id, value, COUNT(*) AS cnt FROM
wp_mrp_rating_item_entry_value
GROUP BY
posts_id,
value
ORDER BY
COUNT(*) DESC
因此foreach循环中的计数将可访问$t->cnt。
您有一个对象数组,这是一个非常好的构造。您所需要做的就是对数组进行处理。
我不能帮助你使用WordPress的表插入机制,但伪代码应该是这样的。
首先,给计数起一个更有用的名字是个好主意
$test = $wpdb->get_results('select
posts_id, value,count(*) as how_many
From wp_mrp_rating_item_entry_value
group by
posts_id, value
order by count(*) desc');
现在处理对象阵列的每次出现
foreach ($test as $obj) {
// Use these fields in an Insert statement
$sql = "INSERT INTO TableName (f1,f2,f3)
VALUES ({$obj->post_id},
{$obj->value},
{$obj->how_many}");
// WP command to issue a query
}
//Just use type cast brother. Use
$test = (array) $test;
//print_r($test);
foreach($test as $item) :
//if you want to place into the db
$wpdb->query( $wpdb->prepare(
"INSERT INTO $wpdb->name_of_wp_table_goes_here
( post_id,value,count )
VALUES (".$item['post_id'].", '".$item['value']."', ".$item['count'].")
%d",
1
) );
endforeach;