Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
添加在key-PHP中具有父值的数组的值_Php_Arrays - Fatal编程技术网

添加在key-PHP中具有父值的数组的值

添加在key-PHP中具有父值的数组的值,php,arrays,Php,Arrays,基本上我有这个数组$data: 我想检查数据[$key]['parent']是否存在于['id']中,如果存在,它会将数组的标题与其父数组连接起来,如下所示: Array ( [produit 1] => Array ( [0] => Sous produit 11 [1] => Sous produit 10 ) [Prod

基本上我有这个数组$data:

我想检查数据[$key]['parent']是否存在于['id']中,如果存在,它会将数组的标题与其父数组连接起来,如下所示:

Array
    (
        [produit 1] => Array
            (
                [0] => Sous produit 11
                [1] => Sous produit 10
            )

        [Produit 2] => Produit 2
        [Produit 3] => Produit 3
        [Produit 4] => Produit 4
    )
以下是我尝试过但没有成功的地方:

foreach ($data as $key => $value) {
        $rslt[$value['id']]= $value;    
    }

$output = array();
foreach ($rslt as $key => $value) {
    if(array_key_exists($value['parent'],$rslt)){
        $new_key = $rslt[$value['parent']]['title'];
        $output[$new_key][] = $value['title'];
    }
    else $output[$value['title']] = $value['title'];
}

我能做到吗?非常有趣。

您试图按标题获取父项,但将父项id另存为键

// create id => data array
foreach($data as $key => $value) {
    $rslt[$value['id']] = $value;
}

$output = array();
// create id => labels array
foreach($rslt as $key => $value) {
    if(array_key_exists($value['parent'], $rslt)) {
        // append title to parent
        $output[$value['parent']][] = $value['title'];
    } else {
        // forgot to add parents 
        $output[$value['id']] = array($value['title']);
    }
}

$final = array();
// create parent label => labels array
foreach($output as $key => $value) {
    $final[$value[0]] = $value; // parent will always be first array item
}

你想用相同的父id对项目进行分组吗?是的@Darren这正是我想要的。抱歉@InShareBits,但这没有输出我需要的数组。@user3350731我的逻辑中有个错误,试试看,请注意,$final将保留您的期望值,直到它呈现的数组与请求的输出不同,因为它添加了一个本身包含child的数组的$key。我说过,$final保留数组而不是$output
// create id => data array
foreach($data as $key => $value) {
    $rslt[$value['id']] = $value;
}

$output = array();
// create id => labels array
foreach($rslt as $key => $value) {
    if(array_key_exists($value['parent'], $rslt)) {
        // append title to parent
        $output[$value['parent']][] = $value['title'];
    } else {
        // forgot to add parents 
        $output[$value['id']] = array($value['title']);
    }
}

$final = array();
// create parent label => labels array
foreach($output as $key => $value) {
    $final[$value[0]] = $value; // parent will always be first array item
}