3

I have two multidimensional array

Array
(
[0] => Array
    (
        [code] => 2079
        [label] => Nike
    )

[1] => Array
    (
        [code] => 1080
        [label] => Adidas
    )    
)

Array
(
[0] => Array
    (
        [manufacturers_id] => 2753
        [manufacturers_name] => Reebok
    )

[1] => Array
    (
        [manufacturers_id] => 2526
        [manufacturers_name] => Adidas
    )

[2] => Array
    (
        [manufacturers_id] => 34
        [manufacturers_name] => Nike
    )

)

I want to do string matching of a key label of array 1 with key manufacturer_name of array 2. What is the best approach in multidimensional arrays ?

1
  • 1
    two foreach loop and and one-one match, because this is a multi-dimensional array with different size. Apr 27, 2016 at 3:40

3 Answers 3

0

You could loop trough the arrays.

foreach ($multi_array1 as $value) {  
    foreach ($multi_array2 as $value2) {
      If ($value[label] === $value2 [manufacturer_name])
   {}
 }
}
0

If you want to match by label and manufacturers_name, then I suggest you reindex your arrays by those fields:

$by_label = [];
foreach($first_array as $element) {
    $by_label[$element['label']] = $element['code'];
}

$by_name = [];
foreach($second_array as $element) {
    $by_label[$element['manufacturers_name']] = $element['manufacturers_id'];
}

foreach($by_label as $label => $code) {
    print "Label is $label, code is $code, id is {$by_name[$label]}";
}

foreach($by_name as $name => $id) {
    print "Name is $name, id is $id, label is {$by_label[$name]}";
}
0

Just use foreach to accomplish your desire result.

Array

$firstArr = array(
        array("code" => 2079, "label" => 'Nike'),
        array("code" => 1080, "label" => 'Adidas')
    );

$secArr = array(
        array("manufacturers_id" => 2753, "manufacturers_name" => 'Reebok'),
        array("manufacturers_id" => 2526, "manufacturers_name" => 'Adidas'),
        array("manufacturers_id" => 34, "manufacturers_name" => 'Nike')
    );

Foreach Technique:

foreach($firstArr as $value){
    if(in_array_sec($value['label'])){
        echo $value['label'].' found in second array.';
    }else{
        echo $value['label'].' not found in second array.';
    }
}

function in_array_sec($val_one){
    global $secArr;
    $flag = false;

    foreach($secArr as $value){
        if($value['manufacturers_name'] == $val_one){
            $flag = true;
            break;
        }
        else
            $flag = false;
    }
    return $flag;
}

Result:

Nike found in second array.

Adidas found in second array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.