ConquestXD
ConquestXD

Reputation: 754

CakePHP find on a json encoded field

I am creating a store in CakePHP and have added a text field which stores a json array of all the categories the store falls into.

How do I do a cake find on all stores that fall into the "gardening" category?

json encoded field:

["gardening","books-and-toys"]

I am thinking some sort of in_array() find but not quite sure.

Many Thanks

Upvotes: 0

Views: 775

Answers (1)

mensch
mensch

Reputation: 4411

You can use the PHP method json_decode and return the JSON object as an associative array by setting the second option of that function to true. You can then call array_search for example to return the corresponding key.

<?php
  $categories = json_decode($json, true);
  $categoryKey = array_search('gardening', $categories);
  $categoryName = $categories[$categoryKey];
?>

You can then use $categoryName in a CakePHP find() call.

Upvotes: 1

Related Questions