我正在尝试创建一种数据结构,使我的应用程序可以使用它来将系统中的类别映射到WooCommerce结构。我只需要一个类别层次结构(如下所示),其中包含具有类别子节点ID的每个父/子级别之间的管道的类别完整路径。
我可以使用以下代码轻松获取WooCommerce中的所有产品类别:
$woocommerce = new Client($this->ecommerce_url,$this->ecommerce_api_key,$this->ecommerce_api_cred,array('wp_api' => true,'version' => 'wc/v1'));
$send_call = true;
$per_page = 30;
$categories = array();
$page = 1;
$categories = array();
while($send_call == true)
{
$result_categories = $woocommerce->get('products/categories', array('per_page'=>$per_page, 'page'=>$page,'context' => 'view'));
$page++;
$categories = array_merge( $categories, $result_categories );
if( count($result_categories) < $per_page )
{
$send_call=false;
}
}
$return_woo_categories = array();
foreach($categories as $index => $category)
{
$return_woo_categories[] = array('name' => $category['name'], 'id' => $category['id'], 'parent' => $category['parent']);
}
$return_woo_categories的var_dump结果
array(13) {
[0]=>
array(3) {
["name"]=>
string(1) "/"
["id"]=>
int(23)
["parent"]=>
int(20)
}
[1]=>
array(3) {
["name"]=>
string(1) "+"
["id"]=>
int(21)
["parent"]=>
int(20)
}
[2]=>
array(3) {
["name"]=>
string(6) "Albums"
["id"]=>
int(20)
["parent"]=>
int(16)
}
[3]=>
array(3) {
["name"]=>
string(18) "Castle On The Hill"
["id"]=>
int(24)
["parent"]=>
int(23)
}
[4]=>
array(3) {
["name"]=>
string(8) "Clothing"
["id"]=>
int(14)
["parent"]=>
int(0)
}
[5]=>
array(3) {
["name"]=>
string(7) "Hoodies"
["id"]=>
int(15)
["parent"]=>
int(14)
}
[6]=>
array(3) {
["name"]=>
string(5) "Music"
["id"]=>
int(16)
["parent"]=>
int(0)
}
[7]=>
array(3) {
["name"]=>
string(10) "My New Cat"
["id"]=>
int(6)
["parent"]=>
int(0)
}
[8]=>
array(3) {
["name"]=>
string(7) "Posters"
["id"]=>
int(17)
["parent"]=>
int(0)
}
[9]=>
array(3) {
["name"]=>
string(12) "Shape of You"
["id"]=>
int(25)
["parent"]=>
int(23)
}
[10]=>
array(3) {
["name"]=>
string(7) "Singles"
["id"]=>
int(18)
["parent"]=>
int(16)
}
[11]=>
array(3) {
["name"]=>
string(8) "T-shirts"
["id"]=>
int(19)
["parent"]=>
int(14)
}
[12]=>
array(3) {
["name"]=>
string(1) "x"
["id"]=>
int(22)
["parent"]=>
int(20)
}
我需要一个数据结构作为输出,其中键的顺序并不重要。
$cat_map = array(
'Clothing' => 14,
'Clothing|Hoodies' => 15,
'Clothing|T-shirts' => 19,
'My New Cat' => 6,
'Posters' => 17,
'Music' => 16,
'Music|Singles' => 18,
'Music|Albums' => 20,
'Music|Albums|x' => 22,
'Music|Albums|/' => 23,
'Music|Albums|+' => 21,
'Music|Albums|/|Castle On The Hill' => 24,
'Music|Albums|/|Shape Of You' => 25,
);
我陷入了困境,不知该如何做;我想我需要使用递归来解决问题;但是让我卡住的是,我从WooCommerce返回的数组顺序没有任何层次结构。(按添加顺序排列,最近的排在最前面)