2

Using the numbers from $ids, I want to pull the data from $nuts.

So for example:

$ids = [0,3,5]; // 0 calories, 3 sugar, 5 fat

$nuts = [
    'calories' => 'cal',
    'protein' => 'pro',
    'carbohydrate' => 'car',
    'sugar' => 'sug',
    'fiber' => 'fib',
    'fat' => 'fat',
];

$returnData = [
    'calories' => 'cal',
    'sugar' => 'sug',
    'fat' => 'fat',
];

I could loop through each $ids number with a foreach(); but I'm curious to see if there is a better method than this?

$newNuts = array_values(array_flip($nuts));
foreach($ids as $i)
    $returnData[$newNuts[$i]] = $nuts[$newNuts[$i]];
0

2 Answers 2

2

I did some work and realized, you don't need array_flip, array_values is fine.

$num_nuts = array_values ($nuts);

for ($z=0; $z<sizeof($ids); $z++) {
 echo $num_nuts[$ids[$z]];            
 }

Just 1 more line of code, but I think it does the job. I think mine is going to be faster because the array_flip basically exchanges all keys with their associated values in an array, which is not what I am doing. It's actually one less pain.

I am simply converting the original array to a new one by index and simply looping upon it. Also, not the elegant way to use the power of PHP available to us, but works just fine. array_flip is O(n), but I think better not use it for larger data-sets.

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

Comments

0

How about a simple array_slice?

$result = array();
foreach ($ids as $i) {
    $result += array_slice($nuts, $i, 1, true);
}

No need to create a copy of the array.

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.