phparraysmultidimensional-arrayfilterarray-difference

Remove a whole row from a 2d array if a blacklisted value is found in a column


In my scenario a paintings list is located in the column in json format. Paintings list contains file name, painting name and view count. I want to delete a painting in the list. But I did not manage. Here is my codes:

$paintings = '[["24ef9-70076-4358c-48386.jpg","La Donna Gravida","649"],["a7972-065a9-4c0f9-723d1.jpg","Madonna and Child with the Book","1254"],["b054c-df208-0f600-e884e.jpg","Madonna del Granduca","1457"]]';
$painting = 'a7972-065a9-4c0f9-723d1.jpg';
$difference  = array_diff((array)json_decode($paintings), (array)$painting);
echo json_encode(array_values($difference));

I am trying to reach the following conclusion:

[["24ef9-70076-4358c-48386.jpg","La Donna Gravida","649"],["b054c-df208-0f600-e884e.jpg","Madonna del Granduca","1457"]]

Unfortunately, I get an error like this:

Notice: Array to string conversion in...


Solution

  • You do not have objects with keys in the json string, so the array you create by decoding it will not be associative with keys. One of the possible ways to solve your problem is shown below (straight forward one).

    $out = array();
    foreach(json_decode($paintings, true) as $p)
      if (!in_array($painting, $p))
        $out[] = $p;
    
    echo json_encode(array_values($out));
    

    Another way

    $out = array_filter(json_decode($paintings, true), function($el) use($painting) {
      return !in_array($painting, $el);  
    });
    
    echo json_encode(array_values($out));
    

    The reason is because ["a7972-065a9-4c0f9-723d1.jpg","Madonna and Child with the Book","1254"] is not an element with key or value a7972-065a9-4c0f9-723d1.jpg - it is another array and you have to check either the existence of the value in the whole sub-array or just its first element. In that case !in_array($painting, $el) can be replaced by $painting != $el[0]