tree em
tree em

Reputation: 21721

Transform array uplevel array elements?

Have an $x as array:

$x1 = array(
   0=>array("up1", -10, 1, 1, 2.5),
   19=>array("up2",-4, 1.2, 2, 0.5)
);

I want to transform $x1 Became x2 like this:

     $x2 = Array(
    'A'=>
        array(
        "up1"=>array(-10, 1, 1, 2.5),
        "up2"=>array(-4, 1.2, 2, 0.5)
        )
      );

Anybody can told help me algorithm to do this:?

Upvotes: 1

Views: 89

Answers (4)

Mike Lentini
Mike Lentini

Reputation: 1358

Here's how I would go about it. Not the best way but, it works fine.

$x1 = array(
  0=>array("up1", -10, 1, 1, 2.5),
  19=>array("up2",-4, 1.2, 2, 0.5)
);

$x2 = array( 'A' => array() );

foreach($x1 as $current) {
  $key = $current[0];
  unset($current[0]);
  $x2['A'][$key] = $current;
}

Upvotes: 0

nanda kumar
nanda kumar

Reputation: 31

please try this out

for ( $i = 0 ; $x1[$i] != NULL ; $i++ ) {
  $x1[$i] = 'a'=>($x1[$i]);
  for ( $j = 0 ; $x1[$i][$j] != NULL; $j++ ) {
    $x1[$i][$j] = 'up'.$j=> $x1[$i][$j];
  }
}

Upvotes: 0

hsz
hsz

Reputation: 152226

$x2 = array();
$i  = 0;
foreach ( $x1 as $data ) {
    if ( empty($x2['A']) ) {
        $x2['A'] = array();
    }

    $x2['A'][ array_shift($data) ] = $data;
}

Upvotes: 1

deceze
deceze

Reputation: 522165

$x2 = array();
foreach ($x1 as $x) {
    $key = array_shift($x);
    $x2['A'][$key] = $x;
}

Or, if you want to be really clever:

$x2 = array();
foreach ($x1 as $x) {
    $x2['A'][array_shift($x)] = $x;
}

Upvotes: 4

Related Questions