0

Im creating an array of products, each with an ID and score:

$savedProducts = array( 'product' => array("product_id" => $product_id,"product_score" => $score)); 

I want to be able to update the score by using the product_id as identifier.

I've tried:

foreach($savedProducts as $key => $val)
{

    if ($val == $property_id )
    {                   
        $savedProducts[$key] = $score;
        break;
    }
}   

Which keeps adding a new array item, rather than updating the original.

I think the issue is that my initial array setup then doesn't match the edited one.

Initial array:

Array
(
    [product] => Array
        (
            [product_id] => 125026
            [product_score] => 5
        )

)

After trying to update score:

Array
(
    [0] => Array
        (
            [product] => Array
                (
                    [product_id] => 125026
                    [product_score] => 4
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [product] => Array
                        (
                            [product_id] => 125026
                            [product_score] => 4
                        )

                )

        )

)

So it keeps addding elements, rather than updating the existing.

3
  • How does $savedProperties look like? Commented Mar 5, 2014 at 15:12
  • With this array structure you can only have one 'product' because new added entries will override the key?! Or is 'product' just a placeholder for something else? Commented Mar 5, 2014 at 15:12
  • You seem to have a savedProducts and a savedProperties, I presume they should be the same. Which would make changing your array a lot easier :-) Commented Mar 5, 2014 at 15:16

2 Answers 2

1

with PHP 5.5 use:

$savedProducts = array_column($savedProducts, NULL, 'product_id');

then you can access your product with:

$savedProducts[$product_id]
Sign up to request clarification or add additional context in comments.

2 Comments

Notice: Undefined offset: 125026 (where the number is my product_id) , thats on PHP5.5.7
can you print_r your $savedProducts and append it to your question
0

Please try this

foreach($savedProducts as $key => $val)
{
if($val['product_id'] == $property_id)
{                   
    $savedProperties[$key]['product_score'] = $score;
    break;
}
} 

1 Comment

I then get Notice: Undefined index: product_id

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.