2

here is my first array

$array1 = Array
(
    [0] => Array
        (
            [class] => Nursery
            [subjects] => Array
                (
                    [0] => dance
                    [1] => Drawing
                    [2] => English
                    [3] => Hindi
                    [4] => Maths
                    [5] => Painting
                    [6] => Reading & Writing

                )

        )

    [1] => Array
        (
            [class] => Kg
            [subjects] => Array
                (
                    [0] => Drawing
                    [1] => English
                    [2] => Hindi
                    [3] => Painting
                    [4] => Personality Development
                )

        )

    [2] => Array
        (
            [class] => 1st
            [subjects] => Array
                (
                    [0] => Art & Craft
                    [1] => Computer
                    [2] => Drawing
                    [3] => English
                    [4] => Environmental Education
                    [5] => French
                    [6] => hand writing
                    [7] => Hindi
                    [8] => Maths
                    [9] => Moral Teaching
                    [10] => music
                    [11] => Painting
                    [12] => Spoken English
                )

        )

);

and the second array is

$array2 = Array
(
    [0] => Array
        (
            [class] => Kg
            [subjects] => Array
                (
                    [0] => English
                    [1] => Hindi
                )

        )

    [1] => Array
        (
            [class] => 1st
            [subjects] => Array
                (
                    [0] => English
                    [1] => Environmental Education
                    [2] => French
                )

        )


);

The desired output I want is like below

$output = Array
(
    [0] => Array
        (
            [classname] => Nursery
            [ischeck] => No
            [subs] => Array
                (
                    [0] => Array
                        (
                            [subjects] => dance
                            [ischeck] => No
                        )

                    [1] => Array
                        (
                            [subjects] => Drawing
                            [ischeck] => No
                        )

                    [2] => Array
                        (
                            [subjects] => English
                            [ischeck] => No
                        )

                    [3] => Array
                        (
                            [subjects] => Hindi
                            [ischeck] => No
                        )

                    [4] => Array
                        (
                            [subjects] => Maths
                            [ischeck] => No
                        )

                    [5] => Array
                        (
                            [subjects] => Painting
                            [ischeck] => No
                        )

                    [6] => Array
                        (
                            [subjects] => Reading & Writing

                            [ischeck] => No
                        )

                )

        )
         [1] => Array
        (
            [classname] => Kg
            [ischeck] => Yes
            [subs] => Array
                (
                    [0] => Array
                        (
                            [subjects] => Drawing
                            [ischeck] => No
                        )

                    [1] => Array
                        (
                            [subjects] => English
                            [ischeck] => Yes
                        )

                    [2] => Array
                        (
                            [subjects] => Hindi
                            [ischeck] => Yes
                        )

                    [3] => Array
                        (
                            [subjects] => Painting
                            [ischeck] => No
                        )

                    [4] => Array
                        (
                            [subjects] => Personality Development
                            [ischeck] => No
                        )

                )

        )
        [2] => Array
        (
            [classname] => 1st
            [ischeck] => Yes
            [subs] => Array
                (
                    [0] => Array
                        (
                            [subjects] => Art & Craft
                            [ischeck] => No
                        )

                    [1] => Array
                        (
                            [subjects] => Computer
                            [ischeck] => No
                        )

                    [2] => Array
                        (
                            [subjects] => Drawing
                            [ischeck] => No
                        )

                    [3] => Array
                        (
                            [subjects] => English
                            [ischeck] => Yes
                        )

                    [4] => Array
                        (
                            [subjects] => Environmental Education
                            [ischeck] => yes
                        )

                    [5] => Array
                        (
                            [subjects] => French
                            [ischeck] => Yes
                        )

                    [6] => Array
                        (
                            [subjects] => hand writing
                            [ischeck] => No
                        )

                    [7] => Array
                        (
                            [subjects] => Hindi
                            [ischeck] => No
                        )

                    [8] => Array
                        (
                            [subjects] => Maths
                            [ischeck] => No
                        )

                    [9] => Array
                        (
                            [subjects] => Moral Teaching
                            [ischeck] => No
                        )

                    [10] => Array
                        (
                            [subjects] => music
                            [ischeck] => No
                        )

                    [11] => Array
                        (
                            [subjects] => Painting
                            [ischeck] => No
                        )

                    [12] => Array
                        (
                            [subjects] => Spoken English
                            [ischeck] => No
                        )

                )

        )
    )

what I have tried so far

$full_array = array();
    foreach($array1 as $k)
    {
         $subarray = array();
        foreach($array2 as $k1)
        {

            if($k['class'] == $k1['class'])
            {
                $classname = $k['class'];

                foreach($k['subjects'] as $s)
                {
                    if(in_array($s,$k1['subjects']))
                    {
                        $sub = array("subjects"=>$s,"ischeck"=>"Yes");
                    }
                    else
                    {
                        $sub = array("subjects"=>$s,"ischeck"=>"No");
                    }
                   array_push($subarray,$sub);
                   $ot1 = array("classname"=>$classname,"subs"=>$subarray);
                   array_push($full_array,$ot1);
                }

            }
            else
            {
                $cname = $k['class'];
                foreach($k['subjects'] as $sb=>$v)
                {
                    $sub = array("subjects"=>$v,"ischeck"=>"No");
                    array_push($subarray,$sub);
                }

                $ot2 = array("classname"=>$cname,"subs"=>$subarray);
                array_push($full_array,$ot2);

            }
        }
    }
    return $full_array;

If the first array has class kg and the second array have class kg then in the new array it should add a new option ischeck Yes and also the same for subjects comparing with array1 and array2 it should add ischeck on output array if the subject is present in array2 then it should add ischeck in output array after subject column.

7
  • on a separate note, are you getting all these arrays via querying a db? Commented Jan 9, 2020 at 10:22
  • yeah I am getting them from two different tables and I just want them separate in another array so I could show that which class and subjects are checked Commented Jan 9, 2020 at 10:25
  • 1
    Through loop it is possible to create an array like your requirement. But that is not an optimised solution. Try to get data in a proper format from query itself. Dont go for unnecessary loops Commented Jan 9, 2020 at 10:25
  • the second array can be in any order and I want the output in order according to the first array Commented Jan 9, 2020 at 10:26
  • @satya you don't need to do this all on application layer, write a query that can bring a desired output and then use that result on application layers. Commented Jan 9, 2020 at 10:29

3 Answers 3

3

firstly I got all the class name which are in array2 by using array column

$chosen_class= array_column($array2,"class");

Then I made another array subclass with classname and ischeck and with all the subjects of array1

   $subclass = array();
    foreach($array1 as $k)
    {
        if(in_array($k['class'],$chosen_class)){
          $a1 = array("classname"=>$k['class'],"ischeck"=>"Yes","subs"=>$k['subjects']);
          array_push($subclass,$a1);    
        }
        else
        {
            $a1 = array("classname"=>$k['class'],"ischeck"=>"No","subs"=>$k['subjects']);
          array_push($subclass,$a1);    
        }

    } 

After that, I applied foreach loop for $subclass array and checked if this loop has ischeck yes then I applied foreach loop for subjects of array2 and put this array into another array and then I got array difference between array1 subjects and array2 subjects , now I have gotten those subjects which are presented in array2 with class and which are not presented in array1 with class then I pushed them into another array with ischeck yes and ischeck no and then I got my full output

here is my final code

$fulloutput = array();

   foreach($subclass as $sb)
   {
       $cls = $sb['classname'];
       $ischeck = $sb['ischeck'];
       $sbarray = array(); 
       $sbarray2 = array();
       if($sb['ischeck']=='Yes')
       {
           foreach($array1 as $sb1)
           {
               if($sb1['class']==$sb['classname'])
               {
                   $sbarray = $sb1['subjects'];
               }
           }
       }

       $diff = array_diff($sb['subs'],$sbarray);
       foreach($diff as $d=>$v)
       {
           $sb2 = array('subs'=>$v,'ischeck'=>'No');
           array_push($sbarray2,$sb2);
       }
       foreach($sbarray as $d=>$v)
       {
           $sb2 = array('subs'=>$v,'ischeck'=>'Yes');
           array_push($sbarray2,$sb2);
       }
       $ft = array("classname"=>$cls,"ischeck"=>$ischeck,"subs"=>$sbarray2);
       array_push($fulloutput,$ft);
   }
   return $fulloutput;
Sign up to request clarification or add additional context in comments.

Comments

3

If you're getting there array from the query and fetch the data in an associative array (if possible), where the class should be a key and subjects should be the value.

Your array1:

$array1 = [
[
    'class' => 'Nursery', 
    'subjects' => [
        'dance',
        'Drawing',
        'English',
        'Hindi',
        'Maths',
        'Painting',
        'Reading & Writing',
    ]
],
[
    'class' => 'Kg', 
    'subjects' => [
        'English',
        'Drawing',
        'Hindi',
        'Painting',
        'Personality Development',
    ]
],
[
    'class' => '1st', 
    'subjects' => [
        'Art & Craft',
        'Drawing',
        'Computer',
        'Environmental Education',
        'English',
        'French',
        'hand writing',
        'Hindi',
        'Maths',
        'music',
        'Painting',
        'Moral Teaching',
        'Spoken English',
    ]
]

];

Your array2:

$array2 = [
[
    'class' => 'Kg', 
    'subjects' => [
        'Hindi',
        'English',

    ]
],
[
    'class' => '1st', 
    'subjects' => [
        'English',
        'French',
        'Environmental Education',
    ]
]

];

Try it with the following code:

// Make an associave array of $array2 if couln'd make it from db query..
$class2 = array_column($array2, 'class');
$sub2 = array_column($array2, 'subjects');
$new_a2 = array_combine($class2, $sub2);

foreach ($array1 as $key => $a1) {
    $subs_final = [];
    // Make an associave array of $array1 if couln'd make it from db query.
    $new_a[$a1['class']] = $a1['subjects'];
    // Prepare output.
    $output[$key] = [
        'classname' => $a1['class'],
        'ischeck' => (in_array($a1['class'], $class2)? 'Yes' : 'No'),
        ];
    foreach ($a1['subjects'] as $key2 => $subject) {
        $subs_final[] = [
                'subjects' => $subject,
                'ischeck' => (isset($new_a2[$a1['class']]) && in_array($subject, $new_a2[$a1['class']])? 'Yes' : 'No'),
            ];
    }
    $output[$key]['subs'] = $subs_final;
}
echo "<pre>"; print_r($output); die();

It can be done even in one loop and for that, you have deep dive into arrays function. But for now, try this.

Here is the output:

Array
(
    [0] => Array
        (
            [classname] => Nursery
            [ischeck] => No
            [subs] => Array
                (
                    [0] => Array
                        (
                            [subjects] => dance
                            [ischeck] => No
                        )

                    [1] => Array
                        (
                            [subjects] => Drawing
                            [ischeck] => No
                        )

                    [2] => Array
                        (
                            [subjects] => English
                            [ischeck] => No
                        )

                    [3] => Array
                        (
                            [subjects] => Hindi
                            [ischeck] => No
                        )

                    [4] => Array
                        (
                            [subjects] => Maths
                            [ischeck] => No
                        )

                    [5] => Array
                        (
                            [subjects] => Painting
                            [ischeck] => No
                        )

                    [6] => Array
                        (
                            [subjects] => Reading & Writing
                            [ischeck] => No
                        )

                )

        )

    [1] => Array
        (
            [classname] => Kg
            [ischeck] => Yes
            [subs] => Array
                (
                    [0] => Array
                        (
                            [subjects] => English
                            [ischeck] => Yes
                        )

                    [1] => Array
                        (
                            [subjects] => Drawing
                            [ischeck] => No
                        )

                    [2] => Array
                        (
                            [subjects] => Hindi
                            [ischeck] => Yes
                        )

                    [3] => Array
                        (
                            [subjects] => Painting
                            [ischeck] => No
                        )

                    [4] => Array
                        (
                            [subjects] => Personality Development
                            [ischeck] => No
                        )

                )

        )

    [2] => Array
        (
            [classname] => 1st
            [ischeck] => Yes
            [subs] => Array
                (
                    [0] => Array
                        (
                            [subjects] => Art & Craft
                            [ischeck] => No
                        )

                    [1] => Array
                        (
                            [subjects] => Drawing
                            [ischeck] => No
                        )

                    [2] => Array
                        (
                            [subjects] => Computer
                            [ischeck] => No
                        )

                    [3] => Array
                        (
                            [subjects] => Environmental Education
                            [ischeck] => Yes
                        )

                    [4] => Array
                        (
                            [subjects] => English
                            [ischeck] => Yes
                        )

                    [5] => Array
                        (
                            [subjects] => French
                            [ischeck] => Yes
                        )

                    [6] => Array
                        (
                            [subjects] => hand writing
                            [ischeck] => No
                        )

                    [7] => Array
                        (
                            [subjects] => Hindi
                            [ischeck] => No
                        )

                    [8] => Array
                        (
                            [subjects] => Maths
                            [ischeck] => No
                        )

                    [9] => Array
                        (
                            [subjects] => music
                            [ischeck] => No
                        )

                    [10] => Array
                        (
                            [subjects] => Painting
                            [ischeck] => No
                        )

                    [11] => Array
                        (
                            [subjects] => Moral Teaching
                            [ischeck] => No
                        )

                    [12] => Array
                        (
                            [subjects] => Spoken English
                            [ischeck] => No
                        )

                )

        )

)

1 Comment

Please put this trick in your php tool belt: 3v4l.org/ce3YF
1

For simplicity and clarity, I'm going to refer your first array as $all and the second array as $selected

Both of the earlier answers are clever enough to know that performance can be improved by modifying your $selected array. However, they only went halfway in preparing the data. For best performance, in_array() should be avoided, even worse is iterated calls of in_array(). The best course of action would be to prepare your $selected array to be a fully associative array and allow php to swiftly check the hashmap by referencing keys exclusively (isset() is far more efficient versus in_array()). In other words, checking keys is ALWAYS faster than checking values. I don't need to do any new benchmarking to support this claim.

Demonstration

  1. Prepare the lookup:

    foreach ($selected as $class) {
        $selectedLookup[$class['class']] = array_flip($class['subjects']);
    }
    var_export($selectedLookup);
    
    • $selectedLookup now contains (the values are irrelevant / not used downscript):

      array (
        'Kg' => 
        array (
          'Hindi' => 0,
          'English' => 1,
        ),
        '1st' => 
        array (
          'English' => 0,
          'French' => 1,
          'Environmental Education' => 2,
        ),
      )
      
  2. Generate the desired result with minimal loops and iterated function calls:

    foreach ($all as $class) {
        $classname = $class['class'];    
        $result[$classname] = [
            'classname' => $classname,
            'ischeck' => 'No',
        ];
        foreach ($class['subjects'] as $subject) {
            if (isset($selectedLookup[$classname][$subject])) {
                $check = 'Yes';
                $result[$classname]['ischeck'] = $check;
            } else {
                $check = 'No';
            }
            $result[$classname]['subs'][] = [
                'subject' => $subject,
                'ischeck' => $check,
            ];
        }
    }
    var_export(array_values($result));
    

    This step declares new data by specifying a temporary first-level associative key ($result[$classname]). When finished iterating, if desirable, remove the temporary keys by calling array_values() on the result array.

Because there are only two loops and only iterated calls of isset() in the result generation step, it will be very difficult if not impossible to find a faster execution of your task.

If this was my application, I might be inclined to declare the "parent" ischeck keys as hasCheck instead -- because I think it will improve human comprehension.

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.