提问人:Lotte_Char 提问时间:10/24/2023 最后编辑:Lotte_Char 更新时间:10/25/2023 访问量:51
遍历 get_posts 以创建嵌套的多维数组和 JSON
Loop through get_posts to create a nested multidimensional array and JSON
问:
我对这个wp_query功能有疑问。我需要创建一个嵌套的JSON,如下所示:
{
"country_zone A": [
{
"tarif_zone A": {
"out": "0.0",
"in": "0.2",
"data": "1"
},
"tarif_zone B": {
"out": "0.0",
"in": "0.2",
"data": "1"
},
" tarif_zoneC": {
"out": "0.0",
"in": "0.2",
"data": "1"
},
"tarif_zone D": {
"out": "0.0",
"in": "0.2",
"data": "1"
}
}
],
" country_zone B": [
{
"tarif_zone A ": {
"out": "0.0",
"in": "0.2",
"data": "1"
},
"tarif_zone B": {
"out": "0.0",
"in": "0.2",
"data": "1"
},
"tarif_zone C": {
"out": "0.0",
"in": "0.2",
"data": "1"
},
"tarif_zone D": {
"out": "0.0",
"in": "0.2",
"data": "1"
}
}
],
"country_zone C": [
{
" tarif_zone A": {
"out": "0.0",
"in": "0.2",
"data": "1"
},
"tarif_zone B": {
"out": "0.0",
"in": "0.2",
"data": "1"
},
"tarif_zone C": {
"out": "0.0",
"in": "0.2",
"data": "1"
},
"tarif_zone D": {
"out": "0.0",
"in": "0.2",
"data": "1"
}
}
]
}
我有与这些字段相对应的 ACF 字段,我需要这个 JSON 来检索 JS 前端中的数据。
这是我的php代码:
add_action('wp_ajax_country_search', 'country_search_callback');
add_action('wp_ajax_nopriv_country_search', 'country_search_callback');
function country_search_callback()
{
header("Content-Type: application/json");
$args_pays = array(
"post_type" => 'pays',
"posts_per_page" => 50,
);
$args_tarif = array(
"post_type" => 'tarif',
"posts_per_page" => 50,
);
$tarifs = get_posts($args_tarif);
$countries = get_posts($args_pays);
if ($countries);
if ($tarifs) {
foreach ($countries as $country) :
setup_postdata($country);
$country_names[] =
get_the_title($country);
$country_zones[] = get_field('pays_id_zone', $country);
endforeach;
foreach ($tarifs as $tarif) :
setup_postdata($tarif);
$tarif_zone[] =
get_field('tarif_dans_id_zone', $tarif);
$tarif_type[] = get_field('tarif_type', $tarif);
$tarif_sens[] = get_field('tarif_sens', $tarif);
$tarif_vers[] = get_field('tarif_vers_id_zone', $tarif);
$tarif_in[] = get_field('tarif_de_id_zone', $tarif);
endforeach;
$premiere_cle[] = array_fill_keys($tarif_zone, $country_zones);
$deuxieme_cle[] = array_fill_keys($country_zones, $tarif_type);
$troisieme_cle[] = array_fill_keys($tarif_type, $tarif_sens);
$quatrieme_cle[] = array_fill_keys($tarif_sens, array($tarif_vers, $tarif_in));
};
echo json_encode($premiere_cle);
wp_die()
}
使用此代码,我获得了以下 JSON 对象:
[{"A":["D","E","B","C","B","B","A","A","Z"],"C":["D","E","B","C","B","B","A","A","Z"],"E":["D","E","B","C","B","B","A","A","Z"],"B":["D","E","B","C","B","B","A","A","Z"],"":["D","E","B","C","B","B","A","A","Z"]}]
如果您明白我的意思,我如何组合所有不同的数组,现在它们都有一个值,该值应该是另一个数组的键?
最后,我试图重新创建这样的东西:https://www.orange.be/fr/options-et-services/international-roaming/tarifs
所有帮助将不胜感激!谢谢!
答: 暂无答案
评论
get_posts()
pays
get_posts
tariff
tarif_zone X
['A' => ['out' => ..., 'in' => ..., ...], 'B' => [...], ...]