anon
anon

Reputation:

return monodimensional-array from multidimensional

I have a multidimensional array:

$array=array( 0=>array('text'=>'text1','desc'=>'blablabla'),
              1=>array('text'=>'text2','desc'=>'blablabla'),
              2=>array('text'=>'blablabla','desc'=>'blablabla'));

Is there a function to return a monodimensional array based on the $text values?

Example:

monoarray($array);
//returns: array(0=>'text1',1=>'text2',2=>'blablabla');

Maybe a built-in function?

Upvotes: 2

Views: 218

Answers (6)

Alix Axel
Alix Axel

Reputation: 154553

Try this:

function monoarray($array)
{
    $result = array();

    if (is_array($array) === true)
    {
        foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value)
        {
            $result[] = $value;
        }
    }

    return $result;
}

Upvotes: 0

ThorDozer
ThorDozer

Reputation: 104

With PHP, you only have to use the function print_r();

So --> print_r($array);

Hope that will help you :D

Upvotes: -1

netcoder
netcoder

Reputation: 67705

If the order of your keys never changes (i.e.: text is always the first one), you can use:

$new_array = array_map('current', $array);

Otherwise, you can use:

$new_array = array_map(function($val) {
    return $val['text'];
}, $array);

Or:

$new_array = array();
foreach ($array as $val) {
    $new_array[] = $val['text'];
}

Upvotes: 0

shamittomar
shamittomar

Reputation: 46692

Do it like this:

function GetItOut($multiarray, $FindKey)
{
   $result = array();
   foreach($multiarray as $MultiKey => $array)
        $result[$MultiKey] = $array[$FindKey];

   return $result;
}

$Result = GetItOut($multiarray, 'text');
print_r($Result);

Upvotes: 1

Radek
Radek

Reputation: 8376

This will return array with first values in inner arrays:

$ar = array_map('array_shift', $array);

For last values this will do:

$ar = array_map('array_pop', $array);

If you want to take another element from inner array's, you must wrote your own function (PHP 5.3 attitude):

$ar = array_map(function($a) {
    return $a[(key you want to return)];
}, $array);

Upvotes: 1

eykanal
eykanal

Reputation: 27017

Easiest way is to define your own function, with a foreach loop. You could probably use one of the numerous php array functions, but it's probably not worth your time.

The foreach loop would look something like:

function monoarray($myArray) {
    $output = array();

    foreach($myArray as $key=>$value) {
        if( $key == 'text' ) {
            $output[] = $value;
        }
    }
    
    return $output;
}

Upvotes: 0

Related Questions