添加到多维关联数组(在PHP中)

时间:2017-09-07 09:11:50

标签: php multidimensional-array

我正在通过具有以下结构的PDO返回一个关联数组:

Array
(
    [0] => Array
        (
            [pesttopicID] => 42
            [sPestName] => CMSM Trap Surveying and Pest Management
            [quizID] => 609
            [bTier1] => 1
            [sDesc] => Workshop assessment
        )

    [1] => Array
        (
            [pesttopicID] => 34
            [sPestName] => Trap Surveyor
            [quizID] => 451
            [bTier1] => 1
            [sDesc] => Competency for CM OAP
        )
)

我想在“内部”数组中添加一个键值对,但是我试图将已发布的解决方案用于添加到关联数组的一般问题...

:
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$newkey='myNewKey';
$newval='myNewValue';
foreach($results as $row){
  $results[][$newkey] = $newval;
  foreach ($row as $key=>$value){
    ... some reporting stuff
    }
}

...导致该对被添加到“外部”数组,例如

Array
(
    [0] => Array <---- I want the new pair in this "inner" array
        (  
            [pesttopicID] => 42
            [sPestName] => CMSM Trap Surveying and Pest Management
            [quizID] => 609
            [bTier1] => 1
            [sDesc] => Workshop assessment
        )

    [1] => Array  <---- I want the new pair in this "inner" array
        (  
            [pesttopicID] => 34
            [sPestName] => Trap Surveyor
            [quizID] => 451
            [bTier1] => 1
            [sDesc] => Competency for CM OAP
        )

    [2] => Array
        (
            [myNewKey] => myNewValue
        )
)

这可能吗?

感谢/汤姆

1 个答案:

答案 0 :(得分:2)

您必须如下所示: -

$newkey='myNewKey';
$newval='myNewValue';
foreach($results as $key=>$row){ //use key now 
  $results[$key][$newkey] = $newval;// remove the second  foreach if not necessary
  //if second foreach is necessary then add it no problem
}

输出: - https://eval.in/856983

或者您也可以这样做: -

// ADD THE INFORMATION AS ORDER ITEM META DATA SO THAT IT CAN BE SEEN AS PART OF THE ORDER
add_action('woocommerce_add_order_item_meta','add_product_custom_field_to_order_item_meta', 9, 3 );
function add_product_custom_field_to_order_item_meta( $item_id, $item_values, $item_key ) {
    // the meta-key is 'Date event' because it's going to be the label too
    if( ! empty( $item_values['selected_date_event'] ) )
        wc_update_order_item_meta( $item_id, 'Date event', sanitize_text_field( $item_values['selected_date_event'] ) );
}

输出: - https://eval.in/856987