Search code examples
phparraysarray-filterarray-column

How can I find the value of and array by searching a value in a different array in the same key in PHP


My Array $json looks like this :

 Array ( 
       [0] => Array ( [poulecode] => 495271
                      [teamcode] => 277986
                      [teamnaam] => JO19-1 (0225 Onder 19 competitie (najaar)) )
       [1] => Array ( [poulecode] => 500027
                      [teamcode] => 277986
                      [teamnaam] => JO19-1 (B3200 Zwaluwen jeugdbeker Onder 19 poule) )
       [2] => Array ( [poulecode] => 524572
                      [teamcode] => 277986
                      [teamnaam] => JO19-1 (0227 Onder 19 competitie (voorjaar)) ) 
       )

How can I pick (set variable $competitiecode) out of the asociated poulecode (524572) by searching the teamnaam's ( JO19-1 (0227 Onder 19 competitie (voorjaar)) ) containing a certain string "voorjaar"?

I have been working on this using array_filter and array_column but I can't seem to figure it out.

This is a piece of my code so far:

$json = json_decode($content_programma, true);

$Poulecode = array_column($json, 'poulecode');
$Teamnaam = array_column($json, 'teamnaam');
$findme = 'voorjaar';
$key = array_filter($findme, array_column($json, $Teamnaam));
$competitiecode = $Poulecode[$key];

Solution

  • <?php
        $array = [
            [
                "poulecode" => 495271,
                "teamcode" => 277986,
                "teamnaam" => "JO19-1 (0225 Onder 19 competitie (najaar)) )"
            ], [
                "poulecode" => 500027,
                "teamcode" => 277986,
                "teamnaam" => "JO19-1 (B3200 Zwaluwen jeugdbeker Onder 19 poule) )"
            ], [
                "poulecode" => 524572,
                "teamcode" => 277986,
                "teamnaam" => "JO19-1 (0227 Onder 19 competitie (voorjaar)) )"
            ]
        ];
    
        $keyword = "voorjaar";
    
        // You can filter your array using array_filter function
        $result = array_filter( $array, function( $item ) use ( $keyword ) {
            return strpos( $item['teamnaam'], $keyword ) !== false;
        });
    
        // and then map result to your datastructure
        $result_ids = array_map( function($item){
            return $item['poulecode'];
        }, $result  );
    
        var_dump($result_ids);