在多维数组PHP中每2个数组合并一次



所以,这对我来说是一个复杂的问题。假设我们有一个数组,如下所示:

{
"data": [

{
"id": "339",
"post_id": "57",
"meta_key": "faq_list_0_question",
"meta_value": "Lorem ipsum dolor sit amet, consectetur adipiscing elit?"
},
{
"id": "341",
"post_id": "57",
"meta_key": "faq_list_0_answer",
"meta_value": "In at neque at nisl fringilla egestas sit amet tincidunt sem. Nunc rutrum risus sit amet metus viverra efficitur pharetra et ante. Aenean at lobortis nisl. "
},
]
}

假设是faq问答多于1,上面的数组将faq问答分离为2个不同的数组,并且假设该数组是第三方API(您无法控制(的结果,我如何合并每2个数组,使faq问答位于1个数组中?

很抱歉问这个问题,我真的很想理解这个问题,但运气不好。我感谢你的回答。

只需循环遍历您的值并将它们添加到一个新数组中。

像这样的

$new_data = [];
foreach($array['data'] as $values) {

//break meta_key into parts
$key_explode = explode('_', $values['meta_key']);
//the last part of $key_explode is the "type" (answer, question)
//array_pop will remove the last array value of $key_explode
$type = array_pop($key_explode);
//implode values back together without "type", will be something like "faq_list_0"
$key = implode('_', $key_explode);

//add to new array. Group by $key, then $type
$new_data[$key][$type] = $values;

}

对于您给出的示例,这将是上面循环的输出。

{
"faq_list_0":{
"question":{
"id":"339",
"post_id":"57",
"meta_key":"faq_list_0_question",
"meta_value":"Lorem ipsum dolor sit amet, consectetur adipiscing elit?"
},
"answer":{
"id":"341",
"post_id":"57",
"meta_key":"faq_list_0_answer",
"meta_value":"In at neque at nisl fringilla egestas sit amet tincidunt sem. Nunc rutrum risus sit amet metus viverra efficitur pharetra et ante. Aenean at lobortis nisl."
}
}
}

这里有一些更接近您在评论中提到的格式。

$new_data = [];
foreach($array['data'] as $values) {

//break meta_key into parts
$key_explode = explode('_', $values['meta_key']);
//the last part of $key_explode is the "type" (answer, question)
//array_pop will remove the last array value of $key_explode
$type = array_pop($key_explode);

//key will be the number at the end of $key_explode (before the type)
$key = array_pop($key_explode);

//add to new array. Group by $key, then $type
$new_data[$key]['id'] = $key;
$new_data[$key][$type] = $values['meta_value']; 

}

输出类似于

[
{
"id":"0",
"question":"Lorem ipsum dolor sit amet, consectetur adipiscing elit?",
"answer":"In at neque at nisl fringilla egestas sit amet tincidunt sem. Nunc rutrum risus sit amet metus viverra efficitur pharetra et ante. Aenean at lobortis nisl. "
}
]

最新更新