Reputation:
Having the following array:
var products = [
{ title: "Product One", categories: ["one", "two"] },
{ title: "Product Two", categories: ["two", "three"] },
{ title: "Product Three", categories: ["three", "four"] }
];
How can I filter the array (I only want products which have category "two") so I get the desired result:
[
{ title: "Product One", categories: ["one", "two"] },
{ title: "Product Two", categories: ["two", "three"] }
]
Upvotes: -1
Views: 123
Reputation: 47874
in_array()
and push qualifying rows into a new result arrayCode: (Demo)
$products = json_decode('[
{ "title": "Product One", "categories": ["one", "two"] },
{ "title": "Product Two", "categories": ["two", "three"] },
{ "title": "Product Three", "categories": ["three", "four"] }
]');
$result = [];
foreach ($products as $row) {
if (in_array('two', $row->categories)) {
$result[] = $row;
}
}
echo json_encode($result, JSON_PRETTY_PRINT);
Output:
[
{
"title": "Product One",
"categories": [
"one",
"two"
]
},
{
"title": "Product Two",
"categories": [
"two",
"three"
]
}
]
Upvotes: 0
Reputation: 3743
Javascript:
products = products.filter(function(item){
return item.categories.indexOf('two') > -1;
});
PHP:
$products = array_filter(
json_decode($products),
function($val) {
return in_array('two', $val->categories);
}
);
But, first you need to correct your json input by double quoting the keys. Below is corrected:
[
{
"title": "Product One",
"categories": [
"one",
"two"
]
},
{
"title": "Product Two",
"categories": [
"two",
"three"
]
},
{
"title": "Product Three",
"categories": [
"three",
"four"
]
}
]
Upvotes: 1
Reputation: 174
$product = '[
{ title: "Product One", categories: ["one", "two"] },
{ title: "Product Two", categories: ["two", "three"] },
{ title: "Product Three", categories: ["three", "four"] }
]';
$productArray = json_decode($product);
foreach($productArray as $key => $value)
{
if(!in_array('two', $value['categories']))
unset($productArray[$key]);
}
$productJson = json_encode($productArray);
echo $productJson;
Upvotes: 1
Reputation: 131
Try to use array_filter http://php.net/manual/en/function.array-filter.php :
print_r(array_filter($array, "value"));
Upvotes: -1