fackz
fackz

Reputation: 531

Search inside multidimensional array and return other key value

I have the following Multidimensional array.

What I'm trying to do is to search for an IDITEM value and if it's found, return the value of the "PRECO" key.

I'm using the following function to check if the value exists and it works fine, but I can't find a way to get the "PRECO" value of the found IDITEM.

Function:

function search_array($needle, $haystack) {
 if(in_array($needle, $haystack)) {
      return true;
 }
 foreach($haystack as $element) {
      if(is_array($element) && search_array($needle, $element))
           return true;
 }
 return false;
}

Anyone can help me with that?

Upvotes: 0

Views: 146

Answers (5)

devpro
devpro

Reputation: 16117

Here is the simple example with array:

// your array with two indexes
$yourArr = array(
        0=>array(
                'IDDEPARTAMENTO'=>'0000000001',
                'DESCRDEPT'=>'Área',
                'ITEM'=>
                array(
                    array(
                        'SETID'=>'RX',
                        'IDITEM'=>'000000000000001367',
                        'DESCRITEM'=>'PISTA TESTE DRIV',
                        'PRECO'=>'1338.78'),
                    array(
                        'SETID'=>'RX',
                        'IDITEM'=>'000000000000001925',
                        'DESCRITEM'=>'PISTA TESTE DRIV2',
                        'PRECO'=>'916'),
                )

            ),
        1=>array(
                'IDDEPARTAMENTO'=>'0000000010',
                'DESCRDEPT'=>'Merch',
                'ITEM'=>
                array(
                    array(
                        'SETID'=>'RX',
                        'IDITEM'=>'000000000000002036',
                        'DESCRITEM'=>'PISTA TESTE DRIV23',
                        'PRECO'=>'200.78'),
                    array(
                        'SETID'=>'RX',
                        'IDITEM'=>'000000000000001608',
                        'DESCRITEM'=>'PISTA CRACHÁ  DRIV4',
                        'PRECO'=>'44341'),
                )                       
        ));

// solution
$newArr = array();
foreach ($yourArr as $value) {
    foreach ($value as $key => $innerVal) {
        if($key == 'ITEM'){
            foreach ($innerVal as $key_inner => $keyinner) {
                if(!empty($keyinner['IDITEM'])){
                    $newArr[$keyinner['IDITEM']] = $keyinner['PRECO'];
                }
            }
        }
    }
}

echo "<pre>";
print_r($newArr);

Result values with IDITEM:

Array
(
    [000000000000001367] => 1338.78
    [000000000000001925] => 916
    [000000000000002036] => 200.78
    [000000000000001608] => 44341
)

Upvotes: 0

Alex Andrei
Alex Andrei

Reputation: 7283

The simplest way is to use a foreach loop twice. Check for the key and store the result into an array for later use.

Based on your array, the below

$search = '000000000000001650';

foreach($array as $element){
    foreach ($element['ITEM'] as $item){
        if (isset($item['IDITEM']) and $item['IDITEM'] == $search){
            $results[] = $item['PRECO'];
        }
    }
}

print_r($results);

Will output

Array
(
    [0] => 375
)

Upvotes: 1

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Use a static variable to remember the status between multiple function calls, and also to store the desired PRECO value. It makes the function remember the value of the given variable ($needle_value in this example) between multiple calls.

So your search_array() function should be like this:

function search_array($needle, $haystack){
    static $needle_value = null;
    if($needle_value != null){
        return $needle_value;
    }
    foreach($haystack as $key => $value){
        if(is_array($value)){
            search_array($needle, $value);
        }else if($needle == $value){
            $needle_value = $haystack['PRECO'];
            break;
        }
    }
    return $needle_value;
}

This function will finally return $needle_value, which is your desired PRECO value from the haystack.

Upvotes: 1

Hassan
Hassan

Reputation: 626

You can change the first if statement to return it instead of returning a boolean :

function search_array($needle, $haystack) {
    if(in_array($needle, $haystack) && array_key_exists('PRECO', $haystack)) {
        return $haystack['PRECO'];
    }
    foreach($haystack as $element) {
        if(is_array($element))
        {
            $result = search_array($needle, $element);
            if($result !== false)
                return $result;
        }
    }
    return false;
}

Upvotes: 1

mloureiro
mloureiro

Reputation: 949

The easiest idea I can remember is converting that boolean search_array into a path creator, where it will return the path for the item, or false if it isn't found.

function get_array_path_to_needle($needle, array $haystack) 
{
  if(in_array($needle, $haystack)) 
  {
    return true;
  }

  foreach($haystack as $key => $element) 
  {
    if(is_array($element) && ($path = get_array_path_to_needle($needle, $element)) !== false)
    {
      return $path === true ? $key : $key . '.' . $path;
    }
  }

  return false;
}

Then, since you already have the path, then rerun the array to fetch the item

function get_array_value_from_path(array $path, array $haystack)
{
  $current = $haystack;
  foreach($path as $key) 
  {
    if(is_array($current) && array_key_exists($key, $current))
    {
      $current = $current[$key];
    }
    else
    {
      return false;
    }
  }

  return $current;
}

This wont get you the PRECO, but it will return the item (array) where id found the value you searched for.

So a simple usage would be:

$path = get_array_path_to_needle('000000000000001650', $data);
$item = get_array_value_from_path(explode('.', $path), $data);
// here you have full array for that item found
print_r($item);
// here you have your price
print_r($item['PRECO']);

Upvotes: 1

Related Questions