Jump to content

how to check for key in multidimentional array and then assign it's values


eche

Recommended Posts

Hi,

 

Could never really get my head around arrays, so can someone please help me understand what I'm missing here.

 

I have an array (size of it does not really matter - at best it will have around 20 elements). It's structure is

['code'] => (array [0] => 'name', [1] => 'description', [2] => 'status')

so example:

['100'] => (array [0] => 'test', [1] => 'this is a test code', [2] => 'allowed')

I want to be able to match code to the one that is being searched and if so, then assign name, description and status to variables for display. At the moment I have:

 

$search = $_GET['code'];
if (in_array($search,$array[$search])) {

$name = $array[$search][0];
$desc = $array[$search][1];
$status = $array[$search][2];

}

 

I get an error message of Warning: in_array() [function.in-array]: Wrong datatype for second argument in /var/... on line ... (the line corresponding to my in_array search)

 

I'm obviously doing something wrong, but what is it?

 

Thanks in advance  :-\

if i am not wrong then search value is in the key of the array and your array declaration is not right. I have changed the code so now and its working. I hope that array is in the right format.

 

Below is the code...

 

$array = array('100' => array(0 => 'test', 1 => 'this is a test code', 2 => 'allowed'));
$search = isset($_GET['code']) ? $_GET['code'] : 101;

if(array_key_exists($search, $array)){
$name = $array[$search][0];
$desc = $array[$search][1];
$status = $array[$search][2];
}else{
echo "Array key does not exists";
}

if i am not wrong then search value is in the key of the array and your array declaration is not right. I have changed the code so now and its working. I hope that array is in the right format.

 

Hi,

 

Thanks - that would work. How could I change that code so that I may use a foreach statement to assign the values to this new array from a flat file database?

 

Something like?:

$results = file()

foreach ($results as $result) {

$explode  = explode("|",$result);
$item['code'] = explode[0];
$item['name'] = explode[1];
$item['desc'] = $explode[2];
$item['status'] = $explode[3];
}

foreach ($item as $key=>$value) {
$array = array($item['code'][$key] => array(0 => $item['name'][$key], 1 => $item['desc'][$key], 2 => $item['status'][$key]));
}

$search = isset($_GET['code']) ? $_GET['code'] : 101;

if(array_key_exists($search, $array)){
$name = $array[$search][0];
$desc = $array[$search][1];
$status = $array[$search][2];
}else{
echo "Array key does not exists";
}

 

Thanks.

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.