在子元素php中推送条目

时间:2019-04-11 10:50:29

标签: php arrays multidimensional-array push

我有一个数组$ final_arr ...给出下面的输出,然后我合并费用并创建一个新数组。

git status

我使用以下代码合并了它们:

git checkout test.c

这在我print_r($ final_arr)时给我下面的输出,因此现在费用总计,数组比以前小。

SELECT e.entity_id AS id,
   v1.value AS name,
   e.sku as sku,
   d1.value AS version
FROM mguu_catalog_product_entity e
LEFT JOIN mguu_catalog_product_entity_varchar v1 ON (e.entity_id = v1.entity_id)
LEFT JOIN mguu_catalog_product_entity_varchar d1 ON (e.entity_id = d1.entity_id)
LEFT JOIN mguu_eav_attribute AS mea ON (v1.attribute_id = mea.attribute_id)
LEFT JOIN mguu_eav_entity_type AS meet ON (meet.entity_type_code = 'catalog_product')
WHERE v1.store_id = 0
AND mea.attribute_code = 'name'
AND mea.entity_type_id = meet.entity_type_id
AND d1.attribute_id = 171;

现在我想在子元素中像这样推送整个对象,但效果不佳。

Array
(
    [0] => Array
        (

            [originator] =>Wayne
            [niche] => Construction
            [fee]=>30
        )

    [1] => Array
        (

            [originator] =>Josh
            [niche] => Construction
            [fee]=>30
        )

   [2] => Array
        (

            [originator] => Wayne
            [niche] => Construction
            [fee]=>50
        )

   [3] => Array
        (

            [originator] => Josh
            [niche] => Construction
            [fee]=>70
        )
)

2 个答案:

答案 0 :(得分:2)

您可以尝试像这样在foreach循环中获取下面子项中的所有值

foreach ($formEntries as $value) {

    if (isset($final_arr[$value['originator']])) {
        $final_arr[$value['originator']]['fee_potential'] = (!empty($final_arr[$value['originator']]['fee_potential']) ? $final_arr[$value['originator']]['fee_potential'] : 0) + (!empty($value['fee_potential']) ? $value['fee_potential'] : 0);
    } else {
        $final_arr[$value['originator']] = $value;
        $data_orgin[]                    = $value['originator'];
    }
    $final_arr[$value['originator']]['sub'][] = $value; // new line for sub index
}

Demo

答案 1 :(得分:1)

只需再添加一行,即可将$value数组放入sub数组

$final_arr = array();

foreach($formEntries as $value){

    if(isset($final_arr[$value['originator']])){
        $final_arr[$value['originator']]['fee_potential'] += $value['fee_potential'];
    } else{
        $final_arr[$value['originator']] = $value;
        $data_orgin[] = $value['originator'];
    }
    // new line
    $final_arr[$value['originator']]['sub'][] = $value;
}