Xavier
Xavier

Reputation: 4017

How to create an array from another with PHP

I got a big array of triggers and condition and i want to extract some of these infos and put in a new array.

Here is a sample of my array:

trigger [
  param1 : 'foo',
  param2: 'bar',
  ...
  name: 'triggerName',

  conditions : [
    param1 : 'foo',
    param2: 'bar',
    value: 3
  ],
  [
    param1 : 'foo',
    param2: 'bar',
    value2: 4
  ]
],
trigger 2: ...

I want to loop on every trigger & param conditons and extract an associative array which should look like this:

['triggerName' => 3],
['triggerName' => 4]

What's the best way to do this ? By best i mean the faster and the more optimize way !

Upvotes: 0

Views: 39

Answers (1)

PressingOnAlways
PressingOnAlways

Reputation: 12356

Just do it, worry about optimization after you have an initial implementation.

There isn't much to optimize here as an array is already loaded into memory, so any operation to loop through it will be fast.

$assArray = array();

foreach ($array as $value) {
    foreach ($value['conditions'] as $condition) {
        $assArray[]=array($value['name'] => $condition['value']);
    }
}

Does the value field increment in number? Is it always consistently called 'value' ? You may have to do some lookup on what the actual key name is.

As long as you make sure this loops only through once, O(n), you should be ok. Update the question with an actual implementation and perhaps we can talk about optimization. But I have a feeling this is a case of premature optimization.

Upvotes: 1

Related Questions