0

I have built a DQL that gave me results that look like this:

array:1598 [▼
  0 => array:3 [▼
    "year" => "2000"
    "total" => "750.00"
    "name" => "Brand #1"
  ]
  1 => array:3 [▼
    "year" => "2000"
    "total" => "845.00"
    "name" => "Brand #2"
  ]
  ..
  ..

As you can see, there are 1598 sub-arrays in the results. There are 100 brands in total and 16 dates (from 2000 to 2015). total is the total value of orders for a given brand in a given year.

I need to build an array that would look something like this:

array:100 [▼
  "Brand #1" => array:3 [▼
  "2000" => "750.00"
  "2001" => "1750.00" 
  ..  
  ]
  "Brand #2" => array:3 [▼
    "2000" => "845.00"
    "2001" => "945.00"
    ..
  ]
  ..
  ..
  1. Is it possible to manipulate the initial array so that I achieve the desired array? If so, do you have an idea on how it can be done?

  2. Or maybe it is the database query should be modified to present the results as desired?

1
  • To answer question 2 we need to see your table structure and query. Commented Feb 26, 2015 at 12:34

2 Answers 2

1

Best way to go is to produce the desired array with the right db query.

if is not possible you can loop the array and reorder it in PHP

$old_array= array(
  0 => array(
    "year" => "2000",
    "total" => "750.00",
    "name" => "Brand #1"
  ),
  1 => array(
    "year" => "2001",
    "total" => "950.00",
    "name" => "Brand #1"
  ),
  2 => array(
    "year" => "2000",
    "total" => "845.00",
    "name" => "Brand #2"
  )
);

$new_array = array();
foreach($old_array as $i=>$data){
    @$new_array[$data['name']][$data['year']] = $data['total'];
}

print_r($new_array);
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for help. You're answer is also THE answer, but I cannot tick both :)
0

You may try the following:

$structuredArr= array();
foreach ($unstructArr as $item) {
  $structuredArr[ $item['name'] ][ $item['year'] ] = $item['total'];
}

Here $unstructArr is your first array which contains the unstructured data i.e.

array:1598 [▼
  0 => array:3 [▼
    "year" => "2000"
    "total" => "750.00"
    "name" => "Brand #1"
  ]
  1 => array:3 [▼
    "year" => "2000"
    "total" => "845.00"
    "name" => "Brand #2"
  ]
  ..
  ..

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.