0

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

for($i=0;i<count($cond);$i++){
    $cond[$i] = $cond[$i][0];
}
4

5 回答 5

3

它可以像这样简单:

$array = array_map('reset', $array);
于 2009-08-04T11:10:45.850 回答
1
// 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));
于 2009-08-04T08:07:49.697 回答
1

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

$destinationArray = array();
for ($sourceArray as $key=>$value) {
    $destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
于 2009-08-04T08:12:49.810 回答
1

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

$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);

您可以阅读数组映射的参考以获得详尽的解释。

您还可以选择使用array_walk的轻微变化(它在“就地”阵列上运行)。请注意,该函数不返回值,并且他的参数是通过引用传递的。

function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
于 2009-08-04T08:30:48.980 回答
0

那应该行得通。为什么它不起作用?你得到什么错误信息?这是我将使用的代码:

$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
        $outArr[$i] = $inArr[$i][0];
}
于 2009-08-04T08:08:31.847 回答