簡體   English   中英

從數組中提取元素,使其僅包含指定索引的值

[英]Extract elements from array so it only consists values of a specified index

我有一個數組

array(
 array('total'=>10,'v'=>3229),
 array('total'=>20,'v'=>3129),
 array('total'=>30,'v'=>3391),
);

有沒有一條線的方式對上述轉換為PHP以下?

array(10,20,30);

您可以使用array_map,但是它需要多於一行,除非您擁有PHP 5.3+:

$original = array(
               array('total'=>10,'v'=>3229),
               array('total'=>20,'v'=>3129),
               array('total'=>30,'v'=>3391),
             );


// Callback function
function valueOnly ($element) {
   return $element['total'];
} 

$result = array_map('valueOnly', $original);

使用PHP 5.3+:

$index = 'total';
$lambda = function ($value) use ($index) { return $value[$index]; };

// Here is the one-liner that can be reused if you save the $lamda-function.
$result = array_map($lambda, $original);

無論哪種方式,我都建議您使用這種方法,因為它可以提高可讀性和可重用性。

總會有分號結尾的句子語言:

foreach ($a as $v){ foreach($v as $k=>$v2) { if($k == 'total') {$r[] = $v2;}}};

現在我不會寫這個。

我可能會寫這個,但是您必須先創建一個函數,該函數總計多於一行(或者不是,但是我拒絕在一行中寫:-))

function get_value($x) {
    return $x['total'];
}

$r = array_map("get_value",$a);

定義一行。 正如Vinko所展示的,在一行上可以有大量的語句。 這是我目前可以想到的最佳單行解決方案(單行代碼是foreach語句):

$arr1 = array(
   array('total'=>10,'v'=>3229),
   array('total'=>20,'v'=>3129),
   array('total'=>30,'v'=>3391),
);

$arr2 = array();
foreach ($arr1 as $item) $arr2[] = $item['total'];

顯然有不止一行,但是我假設您已經初始化了$ arr1和$ arr2數組。

我有兩種非常不錯的方法,它們可以根據您的目的(及其變體)一起工作。

/**
 * Pivots a 2 dimensional array.
 *
 * Turns the column names in a two dimensional array into the rows,
 * using the original array's row indexes as column names.  The input
 * array and its rows may be integer-indexed or a hash.
 *
 * You can optionally specify a column or list of columns to return as rows
 *
 * Example -
 * <pre>
 *
 * input:
 * $aIn => array([0] => array([name] => 'John Doe', [phone] => '555-1000', 'happy'),
 *               [1] => array([name] => 'Fred Doodle', [phone] => '555-2000', 'sad', [title] => 'President'),...
 *
 * output:
 * array([name]  => array([0] => 'John Doe', [1] => 'Fred Doodle',...),
 *       [phone] => array([0] => '555-1000', [1] => '555-2000',...),
 *       [0]     => array([0] => 'happy',    [1] => 'sad',...),
 *       [title] => array([1] => 'President'))
 *
 * </pre>
 * @param  array $aInput    A two dimensional array
 * @param  mixed $mColumns  An array of columns or single column name. If nothing
 *                          passed, then all columns from each input row will become rows
 *                          in the output array.
 * @return array            Pivoted array !!! If a single column name is passed in $mColumns
 *                          The return will be a one-dimensional array; you will get back
 *                          an array of the values for that column.
 */
static function pivot($aIn, $mColumns = null) {

    // Initialize the output
    $aOut = array();
    /*
     * If input list of column names, then initialize, in case the
     * input array is empty or doesn't have those columns
     */
    if (is_array($mColumns) && !empty($mColumns)) {
        foreach ($mColumns as $col) {
            $aOut[$col] = array();
        }
    }
    /*
     * Output array needs to be passed inside an array to be passed by reference.
     */
    // TODO As of PHP 5.2.3, could replace callback arg below with simply "xarray::pivot_row", but production uses 5.1.6
    array_walk($aIn, array("xarray", "pivot_row"), array(&$aOut));
    return (empty($aOut) || is_null($mColumns) ? $aOut : (is_array($mColumns) ? array_intersect_key($aOut, array_flip($mColumns)) : $aOut[$mColumns]));
}

public static function pivot_row($aRow, $mKey, $aSpec) {
    foreach ($aRow as $k => $v) {
        $aSpec[0][$k][$mKey] = $v;
    }
}

討厭的解決方案:

$source = array(
 array('total'=>10,'v'=>3229),
 array('total'=>20,'v'=>3129),
 array('total'=>30,'v'=>3391),
);

$totals = array_map( create_function('$a', 'return $a[\'total\'];'), $source );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM