How to delete array value by one of the elements?

Asked

Viewed 108 times

0

I have the following array:

array(3) { 
   [1]=> array(3) { 
      ["ordem"]=> string(1) "2" 
      ["img"]=> string(66) "banner.jpg" 
      ["chave"]=> string(20) "imagem_5adbea7baefaf" 
    } 
   [2]=> array(3) { 
      ["ordem"]=> int(1) "2" 
      ["img"]=> string(70) "Untitled-6.jpg" 
      ["chave"]=> string(20) "imagem_5adbeb0d0f382" 
   }
}

I need to remove, delete a position from the array depending on the "past key" value. For example if the value passed in the function is "imagem_5adbeb0d0f382" then I have to delete index 2 from the array. Can someone help me?

  • 1

    The community recommends that you answer your own question and accept it as a solution if you have managed to resolve the issue on your own. ;)

2 answers

0

<?php

$foo = [
    1 => ["ordem" => 2, "img" => "banner.jpg", "chave" => "imagem_5adbea7baefaf"],
    2 => ["ordem" => 2, "img" => "Untitled-6.jpg", "chave" => "imagem_5adbeb0d0f382"]
    ];
echo "INICIALIZAÇÃO:";
echo "<pre>";
print_r($foo);
echo "</pre>";
foreach($foo as $chave => $valor) {
    if($valor['chave'] == 'imagem_5adbeb0d0f382') {
        $chave_encontrada = $chave;
        break;
    }
}
if (isset($chave_encontrada)) {
    echo "------------<br>";
    echo "Deletando a chave ".$chave_encontrada.".<br>";
    echo "------------<br>";
    unset($foo[$chave_encontrada]);
}
echo "FINALIZAÇÃO:";
echo "<pre>";
print_r($foo);
echo "</pre>";
echo "------------<br>";

Just for example! Now just create your own function to do this service there.

0

I got it using the following:

foreach ($array as $key => $val) {
 if ($val['chave'] === 'imagem_5adbeb0d0f382' ) {                       
       unset($array[$key]);
   }
 }

Thank you all!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.