1

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:?

4 Answers 4

4
$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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Very cool, didn't know about array_shift(). Always learning something new on here!
@Mike There are a many useful array functions in PHP. Since arrays are what pretty much everything evolves around in PHP, you should really take the time to skim through them. One day you'll find a use for one. @IEnAk ...yet not accepted. :-( (Just kidding, I really don't need the points. ;o)))
1
$x2 = array();
$i  = 0;
foreach ( $x1 as $data ) {
    if ( empty($x2['A']) ) {
        $x2['A'] = array();
    }

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

Comments

0

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];
  }
}

1 Comment

If you're going to use for loops, don't make the condition $x1[$i] != NULL, it throws notices! Also, you have syntax errors with weirdly placed =>s.
0

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;
}

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.