2

I have an array returned from db with this structure:

[0] array(2) {
  ["Brand"] "A"
  ["Family"] "B"
}
[1] array(2) {
  ["Brand"] "A"
  ["Family"] "C"
}
[2] array(2) {
  ["Brand"] "A"
  ["Family"] "D"
}
[3] array(2) {
  ["Brand"] "B"
  ["Family"] "ABC"
}
[4] array(2) {
  ["Brand"] "B"
  ["Family"] "DD"
}

I need to create an array like so:

[0] array(2) {
  ["Brand"] "A" array() {
    "B",
    "C",
    "D"
}
[1] array(2) {
  ["Brand"] "B" array() {
    "ABC",
    "DD"
}

So basically, the Brand should be unique and inside each brand i need a list of families.

1
  • 3
    Have you tried anything? Commented Oct 28, 2015 at 11:43

3 Answers 3

2

Try following, $mainarray is the array you have now

$brand = array();
foreach($mainarray as $v){
    $brand['Brand'][$v['Brand']][] = $v['Family'];
}
Sign up to request clarification or add additional context in comments.

Comments

0

This is a simple array recursion exercise.

Here's some PHP pseudo code:

$output = array();

foreach($array as $i){
//loop through the array returned from the db

$output[$i["brand"]] = array_unique(array_merge($output[$i["brand"]], array($i["Family"])));
//merge the existing families for the brand with the current iteration's, and maintain a set datastructure (no duplicate entries for each family)
}

var_dump($output);

Comments

0

here is what you required:

<?php

$array1=array(array('Brand'=>'A','Family'=>'B'), array('Brand'=>'A','Family'=>'C'), array('Brand'=>'A','Family'=>'D'), array('Brand'=>'B','Family'=>'ABC'), array('Brand'=>'B','Family'=>'DD'));


$brand=array();

        foreach($array1 as $value=>$data){
            foreach($data as $value2=>$data2){
                if($value2=='Family'):
                    if($value<3):
                    $brand['Brand']['A'][]=$data2;
                    else:
                    $brand['Brand']['B'][]=$data2;
                    endif;
                endif;
            }
        }

echo "<pre>";
print_r($brand);
echo "</pre>";  

?>

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.