user482954
user482954

Reputation:

Keep rows in a 2d array where a column's subarray contains a specific value

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

Answers (4)

mickmackusa
mickmackusa

Reputation: 47874

  1. Decode the payload into an array of objects
  2. Make iterated checks with in_array() and push qualifying rows into a new result array
  3. After looping, re-encode the data to be in JSON format.

Code: (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

viral
viral

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

SarDau Mort
SarDau Mort

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

Dave Lin
Dave Lin

Reputation: 131

Try to use array_filter http://php.net/manual/en/function.array-filter.php :

print_r(array_filter($array, "value"));

Upvotes: -1

Related Questions