首页 > 解决方案 > 如何使用 PHP 从多维数组的表数据中删除所有权重元素?

问题描述

在手动将额外的“CAD 数据”列附加到带有表格数据的多维数组之后,不幸的是,我在“CAD 数据”列之前得到了这个糟糕的 [权重] 列。

我的表格数据输出截图

实际上我只想在输出之前再次删除整个 [weight] 列。我尝试了几件事,但没有成功。

Array ( 
    [row_0] => Array ( 
        [col_0] => Order number 
        [col_1] => Size 
        [weight] => 1 
    ) 
    [row_1] => Array ( 
        [col_0] => 502 1001 
        [col_1] => 20 
        [weight] => 2 
    ) 
    [row_2] => Array ( 
        [col_0] => 502 1002 
        [col_1] => 25 
        [weight] => 3 
    ) 
    [row_3] => Array ( 
        [col_0] => 502 1003
        [col_1] => 30 
        [weight] => 4 
    ) 
) 

在我的代码下面:

<?php
$rows = $element['#object']->field_product_data_table['und'][0]['tabledata']['tabledata'];

$header = array_shift($rows);

$attributes = array(
    "id" => "tablefield-0",
    "class" => array("tablefield")
);

// append CAD data column
if (array_key_exists('und', $element['#object']->field_product_step_data)) {
    $header[] = t('CAD data');

    // make index of all entries in table
    $entry_row_id_index = array();
    foreach ($rows as $row_id => &$row) {
        foreach ($row as $entry) {
            $entry_row_id_index[$entry] = $row_id;
        }
    }

    $step_files = $element['#object']->field_product_step_data['und'];

    // add step-file to entry to rows with corresponding order number
    $max_row_length = 0;
    foreach ($step_files as &$file) {
        if (array_key_exists($file['description'], $entry_row_id_index)) {
            $orderNumber = $file['description'];
            $row_id = $entry_row_id_index[$orderNumber];

            $rows[$row_id][] = '<a href="#" class="step-file" data-filename="' . $file['filename'] . '" data-ordernumber="' . $orderNumber . '"></a>';

            $row_length = count($rows[$row_id]);
            if ($row_length > $max_row_length) $max_row_length = $row_length;
        }
    }

    // fill rows so all have same length
    foreach ($rows as $row_id => &$row) {
        for ($i = count($row); $i < $max_row_length; $i++) { 
            $row[] = '';
        }
    }
}
?>

标签: phparrays

解决方案


您可以使用array_map 函数操作数组

$arr = array_map(
    # apply function for each array element
    function ($el) {
        # return modified array elements
        return [
            'col_0'=>$el['col_0'], 
            'col_1'=>$el['col_1']
        ];
    }, 
    $arr
);

上面的代码使用带有匿名函数的 array_map 从源数组接收每个元素,对其进行操作并返回更改的元素


推荐阅读