简体   繁体   中英

How to iterate through multidimentional array and show Index

I am writing a program where i am using Multi-dimensional array. The concept will enter the subject name and index will be shown that who student is studying that subject.

$var= [ 'Abdullah'=>['full_name'=>'Abdullah_Faraz',
                 'Subject'=>['English','Urdu','Maths']],

    'Hamid'=>['full_name'=>'Hamid_Amjad', 
                 'Subject'=>['PHP','Urdu','C++']],

    'Abid'=>['full_name'=>'Abid_Ali',
                 'Subject'=>['OOP','OS','Calculus']],

    'Aqeel'=>['full_name'=>'Aqeel_Bhutta',
                 'Subject'=>['Economics','Statistics','Big_Data']]  

];

foreach ($var as $key => $value) {
 foreach ($value as $key1 => $value1) {
    foreach ($value1 as $value2) {

        if($value2='Urdu'){
            echo $key;
    }       
}
}

Output Abdullah Hamid

but now i want to show the index of those who are not studying Urdu the expected outcome should be

 Abid
 Aqeel

But i don't know how to achieve this.

You can use this

foreach ($var as $key => $value) {
    $lang = $value['Subject'][1];
    if($lang != 'Urdu'){
        echo $key.'<br>';
    }
}

Replace your inner two foreach loops with normal for-loop over array length.

<?php 
for ($x = 0; $x < dim-Length; $x++) {
    echo "The number is: $x <br>";
} 
?>

try this

 foreach ($var as $key => $value) {
     $flag = 0;
     foreach ($value as $key1 => $value1) {
        foreach ($value1 as $value2) {

          if($value2=='Urdu'){
              $flag =1;
              echo $value;
         }       
     }
     if($flag == 0){
         echo $key
     }

}

Please see the below codes:

//study 'Urdu'               
foreach($var as $nickname => $data){
    if (in_array('Urdu', $data['Subject']))
        echo $nickname . "<br>";
}

//not study 'Urdu'
foreach($var as $nickname => $data){
    if (!in_array('Urdu', $data['Subject']))
        echo $nickname . "<br>";

}

This kind of task can be done simpler with functional programming . Basically, you need to filter array of students by some predicate (for example, subjects they study or do not study). We can write higher-order function for this. It will use array_filter :

function filterStudensBySubject($students, callable $subjectCriteria = null)
{
    if (is_null($subjectCriteria)) {
        $subjectCriteria = function ($subject) {
            return true;
        };
    }

    return array_filter($students, function ($student) use ($subjectCriteria) {
        if (!isset($student['Subject'])) {
            return false;
        }

        return $subjectCriteria($student);
    });
}

Then we can write some criterias to supply to this function:

$subjects = ['Urdu'];
$studySubjects = function ($student) use ($subjects) {
    return !empty(array_intersect($student['Subject'], $subjects));
};
$doesNotStudySubjects = function ($student) use ($subjects) {
    return empty(array_intersect($student['Subject'], $subjects));
};

We have used array_intersect to get an array of elements that present in both arrays.

Finally, we can get students who study subjects and who don't:

$studentsWhoStudySubjects = filterStudensBySubject($var, $studySubjects);
$studentsWhoDoNotStudySubjects = filterStudensBySubject($var, $doesNotStudySubjects);

Here is working demo .

This approach will allow you to use the same function with any criteria concerning subject (study only two subject, study no more than three subjects, etc.) without rewriting looping logic.

Addition:

You were asking about displaying keys:

$echoKey = function ($key) {
    echo $key, PHP_EOL;
};

$keys = array_keys($studentsWhoStudySubjects);
array_walk($keys, $echoKey);

echo PHP_EOL;

$keys = array_keys($studentsWhoDoNotStudySubjects);
array_walk($keys, $echoKey);

Read about array_keys and array_walk .

This may look like a lot of code for such trivial task. But this approach helps you to learn to write decoupled reusable code. As I mentioned we can use our filterStudensBySubject function to filter students by any condition (that regards subject) without the need to rewrite the function itself.

My bit contribution if we want to check multiple Subjects

 $arr= array('English','Urdu','Big_Data');

  //study 'Urdu'
    foreach ($var as $key => $data) {
        if (array_intersect($arr, $data['Subject'])) {
            echo $key . "<br>";
        }
    }

This will compare $arr with all the Subjects and return the Index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM