0

i have an multidimension array as given below.The array is uniform in structure

I want to make it into two arrays with even and odd keys

$array = array(
array(P0=>"a",P1=>"b",P2=>"c",P3=>"d"),
array(P0=>"e",P1=>"f",P2=>"g",P3=>"h"),
array(P0=>"k",P1=>"l",P2=>"m",P3=>"n"),
array(P0=>"0",P1=>"p",P2=>"q",P3=>"r"),
array(P0=>"s",P1=>"t",P2=>"u",P3=>"v")
);

the result should be as given below.

$array1 = array(
array(array(P0=>"a",P2=>"c"),
  array(P0=>"e",P2=>"g"),
  array(P0=>"k",P2=>"m"),
  array(P0=>"o",P2=>"q"),
  array(P0=>"s",P2=>"u")
)

$array2 = array(
array(array(P0=>"b",P2=>"d"),
  array(P0=>"f",P2=>"h"),
  array(P0=>"l",P2=>"n"),
  array(P0=>"p",P2=>"r"),
  array(P0=>"t",P2=>"v")
) ;

My code is as given below ,how to proceed..

foreach ($array as $key=>$value)
            {
                for($i=2; $i<count($value);$i+=2)
                {
              print_r($value[$i]);
        }
     }

3 Answers 3

0

I think you can use to separate the Mulitdim. array

the extract method

http://us.php.net/extract

Sign up to request clarification or add additional context in comments.

Comments

0

You can extract the integer part of your keys and split them in a foreach loop.

<?php

$array = array(
    array('P0' => "a", 'P1' => "b", 'P2' => "c", 'P3' => "d"),
    array('P0' => "e", 'P1' => "f", 'P2' => "g", 'P3' => "h"),
    array('P0' => "k", 'P1' => "l", 'P2' => "m", 'P3' => "n"),
    array('P0' => "0", 'P1' => "p", 'P2' => "q", 'P3' => "r"),
    array('P0' => "s", 'P1' => "t", 'P2' => "u", 'P3' => "v")
);

$odd = array();
$even = array();

foreach ($array as $a) {
    $e = $o = array();

    foreach ($a as $k => $v) {
        // Extract the int part and check for odd/even
        $i = (int) substr($k, 1);

        if ($i % 2 == 0) {
            $e[$k] = $v;
        } else {
            $o[$k] = $v;
        }
    }

    $odd[] = $o;
    $even[] = $e;
}

var_dump($odd);
echo "<br />";
var_dump($even);
?>

2 Comments

Do you extracted the key values too ?
@AncientGeek Yes. You can run the file by copying this code, works as the OP asked.
0

Another solution. Here's my eval.in.

$array = array(
  array(P0=>"a",P1=>"b",P2=>"c",P3=>"d"),
  array(P0=>"e",P1=>"f",P2=>"g",P3=>"h"),
  array(P0=>"k",P1=>"l",P2=>"m",P3=>"n"),
  array(P0=>"0",P1=>"p",P2=>"q",P3=>"r"),
  array(P0=>"s",P1=>"t",P2=>"u",P3=>"v")
);

$array2 = array();

foreach ($array as $key1 => &$value)
{
  foreach ($value as $key2 => $value2)
  {
       if($key2[1]%2 == 1) {
          $array2[$key1][$key2] = $value[$key2];
          unset($value[$key2]);
       }
  } 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.