简体   繁体   中英

pulling object/array by value json vs arrays

The scenario is an ajax request fetches a json response which contains a product_id among other values in each object, I already have a php variable which contains an array of product objects (laravel collection) so I don't want to pull these again adding another join to my query and slowing things down.

So I have 2 options as far as I can see either write my phone object to a json object stored in a js variable or as an associative array. The problem is the only way I can see of accessing the data I need ie product.make product.name is by running a for loop on either the array or the objects whilst looping through the each object of the json returned by the ajax request so a nested loop which isn't ideal.

My question is, is there a way to pull just the object or array needed by a given keys value? Sorry if that's not very clear, it was the best way I could explain it.

Thanks in advance :)

In PHP, you can use array_intersect_key and array_flip to accomplish this:

$map = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$array_of_keys = array('b', 'd');

var_dump(
    array_intersect_key( $map, array_flip($array_of_keys) )
);

/*
array(2) {
  ["b"]=>
  int(2)
  ["d"]=>
  int(4)
}
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM