Search code examples
phparraysmultidimensional-arrayfetchkey

Extract equal values for multidimensional array in php


I have this problem. I have a multidimensional json array (don't ask - legacy code). I convert it to PHP array. I need to extract all KEYS that have EQUAL VALUE (in my case "666"). I need each key to be assign to a SEPARATE variable. In my code I succeeded to fetch the keys but I can assign them only to another array or all at once to a single variable. Please HELP!!!

Love V

Here is the code:

<?php
//user input
$in = "666";

$outputZ = '[
{"record_id_001":"1"},
{"record_id_002":"13"},
{"record_id_003":"666"},
{"record_id_004":"72661781"},
{"record_id_005":"8762"},
{"record_id_006":"666"},
{"record_id_007":"8762"},
{"record_id_008":"666"},
{"record_id_009":"8762"},
{"record_id_010":"8762"},
{"record_id_011":"666"}
]';

//convert json to php array
//someArray = json_decode($someJSON, true);
$decoZ = json_decode($outputZ, true);

// TESTING (move to comment latter)
//print_r ($decoZ);

//loop through each array an check for user input
//way 1: assign to new array
foreach($decoZ as $array => $number)
foreach($number as $key => $value)
    if (in_array("$in", $number)) {
        $var = $key;
        $getarray = "'" . $var . "'";
        $recnumber = array($getarray);
        print_r ($recnumber);
        }

//way 2: assign to variable 
foreach($decoZ as $array => $number)
foreach($number as $key => $value)
    if (in_array("$in", $number)) {
        $var = $key;
        echo "$var" . " ";
        }
?>

Solution

  • You're overwritting your array on each iterations $recnumber = array($getarray);

    I would rather follow this logic :

    <?php
    //user input
    $in = "666";
    
    $outputZ = '[
    {"record_id_001":"1"},
    {"record_id_002":"13"},
    {"record_id_003":"666"},
    {"record_id_004":"72661781"},
    {"record_id_005":"8762"},
    {"record_id_006":"666"},
    {"record_id_007":"8762"},
    {"record_id_008":"666"},
    {"record_id_009":"8762"},
    {"record_id_010":"8762"},
    {"record_id_011":"666"}
    ]';
    
    $decoZ = json_decode($outputZ, true);
    
    
    // create empty array
    $recnumber = [];
    foreach($decoZ as $record)
    {
        foreach($record as $key => $value)
        {
            // simply compare input with current value
            if ($value === $in)
            {
                // add the key to the previously created array
                $recnumber[] = $key;
            }
        }
    }
    
    var_dump($recnumber);
    

    This outputs :

    array(4) {
    [0]=>
    string(13) "record_id_003"
    [1]=>
    string(13) "record_id_006"
    [2]=>
    string(13) "record_id_008"
    [3]=>
    string(13) "record_id_011"
    }