Jump to content

search on array


prakash

Recommended Posts

Hi,

 

I have following data output from the code that builds associative array from session data and the output is stored as a variable:

 

Array

(

    [0] => Array

        (

            [productID] => 1

            [productType] => ecards

            [printSize] => 2

        )

 

    [1] => Array

        (

            [productID] => 3

            [productType] => wallpapers

            [printSize] => 1

        )

 

)

 

now I need to check 2 data (productID and productType) from the array if any data already exist or not.

Suppose I have a data (productID="1", productType="custom", printSize="2") then how can I do it?

I tried to use array_key_exists but it doesn't work because value for productID may not be unique when value of productType is changed.

 

So in this example (productID="1", productType="custom", printSize="2") how can I check if that data exist or not?

I need to check both productID and productType here.

Link to comment
https://forums.phpfreaks.com/topic/120152-search-on-array/
Share on other sites

Try this:

 

<?php
$arr = array(/* your array here */);
foreach($arr as $key){
     if(in_array('ecards', $arr[$key]['productType'])){
          //do something
     }
}
?>

 

As far as I know there isn't a shorter way to search the array, other then iterating through all the main keys. You can create a function for easier use:

<?php
function searchArray($array, $searchfor, $searchin){
     foreach($array as $key){
          if(in_array($searchfor, $array[$key][$searchin])){
               return true;
          }
     }
}

$mydata = array(/* your array data here */);
if(searchArray($mydata, 'ecards', 'productType')){
     echo 'Value found';
}
?>

Link to comment
https://forums.phpfreaks.com/topic/120152-search-on-array/#findComment-619015
Share on other sites

I got confused in your code. may be you have misunderstood what I am trying to say.

I need to find solution for below:

 

<?php
$multiArray=Array
(
    Array
(
	"productID" => "1",
	"productType" => "ecards",
	"printSize" => "2"
), 

    Array
(
	"productID" => "3",
	"productType" => "wallpapers",
	"printSize" => "1"
)

);

$productID_Check=1;
$productType_Check="custom";

// How to check if the array on $multiArray having productID value 1 (i.e. productID_Check value) and productType value custom (i.e. productType_Check value) exist or not.
?>

Link to comment
https://forums.phpfreaks.com/topic/120152-search-on-array/#findComment-619031
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.