0

On Symfony 3.3, doctrine 2.5 and PHP 5.5.9

My front is sending my API an array that looks like

[{id: 1, value: 2}, {id: 2, value: 2423}, {id: 56, value: 323.3}]

And I need to update my entity with all those values.

I've came across this

foreach ($repo->findById($ids) as $obj) {
    $obj->setOrder(array_search($obj->getId(), $ids));
}

$em->flush();

But can't work my mind on own to make it work to update the values from my array.

What is the best way to update each values of the entities, using the inputted array ?

Victor Jozwicki
  • 700
  • 2
  • 10
  • 24
  • `array_search` searches for value in flat array. You have array of arrays. Either rebuild it to key->value, or iterate everytime to find the requred value. – u_mulder Oct 22 '19 at 15:03

1 Answers1

2
$data = json_decode('[{id: 1, value: 2}, {id: 2, value: 2423}, {id: 56, value: 323.3}]', true);

// After decoding your data - build idValue map - 
// array where key is `id` field and value is `value` field
$idValueMap = array_column($data, 'value', 'id');

// using `array_keys` you can find all items with required ids     
foreach ($repo->findById(array_keys($idValueMap)) as $obj) {
    // and `$idValueMap[$obj->getId()]` will give you the required value for update
    $obj->setOrder($idValueMap[$obj->getId()]);
}

$em->flush();
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • Works exactly as I wanted. Wondering if this is the most optimized version or not – Victor Jozwicki Oct 23 '19 at 12:50
  • I'm not sure but raw sql can be faster, something like `UPDATE tbl SET field = value WHERE ...`, but as you do multiple updates, I'm not sure how can you create and execute one query. – u_mulder Oct 23 '19 at 12:53