CQM
CQM

Reputation: 44278

php turn this array into integer series

this is the output of my array

[["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"]]

but I would like this to look like

[1,1,1,1,1,1,1]

how would this be achieved in php, it seems everything I do gets put into an object in the array, when I don't want that. I tried using array_values and it succeeded in returning the values only, since I did have keys originally, but this is still not the completely desired outcome

Upvotes: 0

Views: 72

Answers (2)

hfcorriez
hfcorriez

Reputation: 112

$yourArray = [["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"]];

use following code in PHP 5.3+

$newArray = array_map(function($v) {
    return (int)$v[0];
}, $yourArray);

OR use following code in other PHP version

function covertArray($v) {
    return (int)$v[0];
}

$newArray = array_map('covertArray', $yourArray)

Upvotes: 1

Jeremy Harris
Jeremy Harris

Reputation: 24579

You could always do a simple loop...

$newArray = array();

// Assuming $myArray contains your multidimensional array
foreach($myArray as $value)
{
   $newArray[] = $value[0];
}

You could beef it up a little and avoid bad indexes by doing:

   if( isset($value[0]) ) {
      $newArray[] = $value[0];
   }

Or just use one of the many array functions to get the value such as array_pop(), array_slice(), end(), etc.

Upvotes: 0

Related Questions