0

I have an array of objects where the reference is not the same as the code_cip.

Array ( 
[9921279] => lignecatalogue Object ( [id] => 3013181 [reference] => 9921279 [commentaire] => [code_cip] => 9884064 )
[9884064] => lignecatalogue Object ( [id] => 3013193 [reference] => 9884064 [commentaire] => [code_cip] => 9884064 )
)

What i am trying to accomplish is to update only the [reference] => 9921279 on the first item to [reference] => 9884064. The [reference] will be updated only if it is not equal to its code_cip. So far i am stuck on the code below.

$arrLigneCats = getAllCat(); //returns above array

foreach($arrLigneCats as $ligneCat) {
    if ($ligneCat->code_cip != $ligneCat->reference) {
        $reference = $ligneCat->reference;
    } else {
        $reference = $ligneCat->code_cip;
    }
}

Anyone has any idea of how to replace the key without the removing the entire line?

3
  • Problem! Should you also be amending the key as well as that seems to match the reference Commented Sep 2, 2022 at 10:22
  • Pass the $ligneCat by reference, like this foreach($arrLigneCats as &$ligneCat) { Commented Sep 2, 2022 at 10:24
  • Then $ligneCat->reference = $ligneCat->code_cip; Commented Sep 2, 2022 at 10:24

1 Answer 1

0

If I have understood your question correctly, the problem is that $reference is just a variable, what you have to change is the reference property of the object. So it will be:

$arrLigneCats = getAllCat(); //returns above array

foreach($arrLigneCats as $ligneCat) {
    if ($ligneCat->code_cip != $ligneCat->reference) {
        $ligneCat->reference = $ligneCat->code_cip;
    }
}

Does it answer your question?

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

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.