-1

php create multidimensional array from flat one

Tried this but counting backwards won't work as I need to move from start to finish in the order in which the array is originally.

I have a simple array:

0 => Item #1
1 => Item #2 
2 => Item #3

I need to create an associative array from the above like so:

Item #1 
  => Item #2 
    => Item #3

Where each value becomes the key for the parent item. This must be done in a while loop not recursion. It MUST move forward, the loop performs a look-ahead for validation purposes, so the original order is imperative

Thanks

EDIT - this is giving me the intended result I just can't get my around how to do this in the main loop |

array:3 [
  0 => "workorder"
  1 => "company"
  2 => "name"
]

$array['workorder'] = [];
$temp = &$array['workorder'];
$temp['company'] = [];

$temp2 = &$temp['company'];
$temp2['name'] = [];

dump($array);
exit;

EDIT 2 | Main loop

$type = current($types);
while (array_key_exists($type, $this->types)) {
    $nextType = next($types);

    // ... do stuff 

    $type = $nextType;
}

return $array;
5
  • Can you add what you have tried so far. Commented Nov 10, 2018 at 20:49
  • It is literally one or two lines causing me issues - I have experimented with something like $temp2 = $array[$type]; $array &= $temp2; but that gives me undefined index notices, and simply doesn't work. I might have to change the implementation to move backwards, wrapping each child in it's parent element - however that requires re-working a bunch of code that breaks out of the loop so please excuse my hesitation to do so :) Commented Nov 10, 2018 at 20:59
  • For what it is worth I have a look-ahead involved so I actually know the current element and the next (if any) Commented Nov 10, 2018 at 21:01
  • What does the main loop look like? Commented Nov 10, 2018 at 21:39
  • I added what I am trying to work into the loop - as a series of hardcoded instructions it works as expected but obviously I need this to be dynamic :p I also threw in the main loop - its just a simple while() but as it steps through each element, it performs a look-ahead to validate each step. Commented Nov 10, 2018 at 21:43

1 Answer 1

0

Try

// This array contain the keys for associative array
    $arrayKeys = ['name1', 'name2', 'name3'];

    // This array contain the values for associative array
    $arrayItems = ['item1', 'item2', 'item3'];

    // this array will be the associative array
    $newArray = [];      
    $count = count($arrayKeys) -1;
    while( $count >= 0 ){
        $newArray[ $arrayKeys[$count] ] = $arrayItems[$count];
        echo '<Br>';
        $count--;
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.