我正在使用WordPress小部件来输出特定帖子类型(Projects)的表格,其中包含2个必填字段。收到的数据是" location"和"权力"。我想添加一个功能,将所有" power"变量,格式化为数字,如果"位置"已经创建。
例如,如果创建3个不同的项目帖子:
"location"=> Winnipeg, MB "power"=>2,
"location"=> Winnipeg, MB "power"=>5,
"location"=> Saskatchewan, AB "power"=>2
然后我希望输出为:
"location"=> Winnipeg, MB "power"=>7,
"location"=> Saskatchewan, AB "power"=>2
我的代码:
<?php
$all_locations=array();
$all_projects=array();
while ( $the_query->have_posts() ):
$the_query->the_post();
global $post;
$id = $post->ID;
$project_location = get_field('location');
$single_kilowatts = get_field('kilowatts');
$single_location = $project_location['address'];
array_push($all_locations, $single_location);
$project_entry=array(
$single_location,
$single_kilowatts
);
$project_entry = compact('single_location','single_power');
array_push($all_projects, $project_entry);
endwhile;
$unique = array_unique($all_locations);
print_r($unique);
print_r($all_projects);
?>
到目前为止,这一切都有效,最后两行将打印出来:
Array ( [0] => Winnipeg, MB [1] => Saskatchewan, AB)
Array ( [0] => Array ( [single_location] => Winnipeg, MB [total_kW] => 2 )
[1] => Array ( [single_location] => Winnipeg, MB [total_kW] => 5 )
[2] => Array ( [single_location] => Saskatchewan, AB [total_kW] => 2 ) )
在此之后,我完全迷失了,并且不知道如何以我在开头提到的方式输出数据。我应该开始一个新的while循环还是使用foreach?我怎样才能最有效地构建我的if语句?
如果您对我的语法有任何答案或提示,请告诉我。我是一名初级开发人员,对php知之甚少,我很高兴听到任何提示或技巧。
答案 0 :(得分:0)
您可以尝试使用以下代码:
$all_projects=array();
while ( $the_query->have_posts() ):
$the_query->the_post();
global $post;
$id = $post->ID;
$project_location = get_field('location');
$single_kilowatts = get_field('kilowatts');
$single_location = $project_location['address'];
$all_projects[$project_location['address']] = (isset($all_projects[$project_location['address']]))?$all_projects[$project_location['address']] + $single_kilowatts : $single_kilowatts;
endwhile;
$unique = array_keys($all_projects);;
print_r($unique);
print_r($all_projects);