1

I have two tables - I want to compare their values. If the $xml codes are in the $db, I create the product_db variable, if not - I will display the echo with the relevant information. Unfortunately - I get information undefined offset. I tried with $xml[0] as $product_xml, although it displays the malfunction of the function and only gets the first index of the array - while I need to compare all.

$xml = array(
    array(
        "code" => 456,
        "stock" => 33,
        "price" => 249.00,
    ),
    array(
        "code" => 789,
        "stock" => 0,
        "price" => 199.00,
    ),
);

$db = array(
    array(
        "code" => 456,
        "stock" => 432,
        "price" => 251.00,
    ),
    array(
        "code" => 789,
        "stock" => 1,
        "price" => 299.00,
    ),
);

foreach ($xml as $product_xml) {

    if (in_array($product_xml['code'], array_column($db, 'code'))) {

        $product_db = $db[$product_xml['code']];
        $update = false;

    } else {

        echo 'error';
    }

}
1
  • 1
    what is your expected output ? Commented Sep 13, 2017 at 6:14

1 Answer 1

1

Actually you have to use array_search() here like below:-

foreach ($xml as $product_xml) {
   $key = array_search($product_xml['code'],array_column($db,'code')); //check value exist in $db array or not and get the key
    if ($key!==false) {
        $product_db = $db[$key]; //based on key get the value form $db array and assign it to $product_db
        print_r($product_db);// print assigned valued
        $update = false;
    } else {
        echo 'error';
    }
}

Output:- https://eval.in/860464

Note:- In your code $update is no where defined.So first defined it before foreach() and then use it. Also i am unable to see any significance of this variable in your code(because you used it no-where)

Sign up to request clarification or add additional context in comments.

4 Comments

The update variable is supposed to serve as a flag, based on which I will determine whether the product is suitable for updating or not.
I test myself - I have 8 minutes for it, then I give you the best answer. It seems to work, but if I had further problems - would you be able to help me?
For further problems you have to ask new question. You will get answers for-sure
Okay, although your solution seems to be the most correct. In a few minutes I will mark the answer as the best one.

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.