代码之家  ›  专栏  ›  技术社区  ›  Supernovah

从2d数组中每个值的第一个成员生成1d数组php

  •  0
  • Supernovah  · 技术社区  · 15 年前

    你怎么能这样做?我在这里看到的代码不起作用

    for($i=0;i<count($cond);$i++){
        $cond[$i] = $cond[$i][0];
    }
    
    5 回复  |  直到 15 年前
        1
  •  0
  •   Hosam Aly    15 年前

    那应该管用。为什么不起作用?您收到什么错误消息? 这是我将使用的代码:

    $inArr;//This is the 2D array
    $outArr = array();
    for($i=0;$i<count($inArr);$i++){
            $outArr[$i] = $inArr[$i][0];
    }
    
        2
  •  3
  •   eisberg    15 年前

    可以这么简单:

    $array = array_map('reset', $array);
    
        3
  •  1
  •   Benedict Cohen    15 年前

    如果源数组不是数字索引,则可能存在问题。试试这个:

    $destinationArray = array();
    for ($sourceArray as $key=>$value) {
        $destinationArray[] = $value[0]; //you may want to use a different index than '0'
    }
    
        4
  •  1
  •   Mez    15 年前
    // Make sure you have your first array initialised here!
    $array2 = array();
    foreach ($array AS $item)
    {
        $array2[] = $item[0];
    }
    

    假设以后要使用相同的变量名,可以将新数组重新分配给旧数组。

    $array = $array2;
    unset($array2); // Not needed, but helps with keeping memory down
    

    另外,根据数组中的内容,您可能能够执行类似的操作。

    $array = array_merge(array_values($array));
    
        5
  •  1
  •   Eineki    15 年前

    如前所述,您的代码在各种情况下都不能正常工作。 尝试使用以下值初始化数组:

    $cond = array(5=>array('4','3'),9=>array('3','4'));
    

    对我来说,更容易阅读的解决方案还包括以下代码:

    //explain what to do to every single line of the 2d array
    function reduceRowToFirstItem($x) { return $x[0]; }
    
    // apply the trasnformation to the array
    $a=array_map('reduceRowTofirstItem',$cond);
    

    你可以阅读 reference for array map 为了一个彻底的解释。

    您也可以选择使用 array_walk (它在阵列上“就地”操作)。注意,函数不返回值,其参数是通过引用传递的。

    function reduceToFirstItem(&$x) { $x=$x[0]; }
    array_walk($cond, 'reduceToFirstItem');