Supernovah
Supernovah

Reputation: 2044

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work

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

Upvotes: 0

Views: 1430

Answers (5)

Eineki
Eineki

Reputation: 14959

As previously stated, your code will not work properly in various situation. Try to initialize your array with this values:

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

A solution, to me better readable also is the following code:

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

You can read the reference for array map for a thorough explanation.

You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.

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

Upvotes: 1

eisberg
eisberg

Reputation: 3771

It can be as simple as this:

$array = array_map('reset', $array);

Upvotes: 3

Marius
Marius

Reputation: 58949

That should work. Why does it not work? what error message do you get? This is the code I would use:

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

Upvotes: 0

Mez
Mez

Reputation: 24953

// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
    $array2[] = $item[0];
}

Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.

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

Also, you might be able to, dependant on what is in the array, do something like.

$array = array_merge(array_values($array));

Upvotes: 1

Benedict Cohen
Benedict Cohen

Reputation: 11920

There could be problems if the source array isn't numerically index. Try this instead:

$destinationArray = array();
for ($sourceArray as $key=>$value) {
    $destinationArray[] = $value[0]; //you may want to use a different index than '0'
}

Upvotes: 1

Related Questions