Jump to content

[SOLVED] extracting specific elements from array


rndilger

Recommended Posts

Hello, I've got an array of mysql field names and I need to create a subset of these array elements (see code below). I would like to extract all of the array elements that begin with 'mem_' as these are the columns in the table that specify information pertaining to members. I presume there is a very easy way to accomplish this, but I'm currently at a loss.

 

Thanks for your help in advance.

 

Ryan

 

$field_names = array();
$cols = mysql_query("SHOW COLUMNS FROM `map`");
for($i=0; $i<mysql_num_rows($cols); $i++){ array_push($field_names,mysql_result($cols, $i)); }

try this

<?php
$field_names = array();
$cols = mysql_query("SHOW COLUMNS FROM `map`");
while($fields = mysql_fetch_assoc($cols))
{
$f = $fields['Field'];
if(substr(0,4) == "mem_")
{
	$field_names[] = $f;
}
}
echo"<pre>";print_r($field_names);

try this

<?php
$field_names = array();
$cols = mysql_query("SHOW COLUMNS FROM `map`");
while($fields = mysql_fetch_assoc($cols))
{
$f = $fields['Field'];
if(substr(0,4) == "mem_")
{
	$field_names[] = $f;
}
}

 

I like the concept and I believe you're onto something. However, when I run the code, it just outputs 'Array' instead of the name.

 

Ryan

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

 

Change MadTechie's code to:

<?php
$field_names = array();
$cols = mysql_query("SHOW COLUMNS FROM `map`");
while($fields = mysql_fetch_assoc($cols))
{
if(substr($fields['Field'],0,4) == "mem_")
	$field_names['Field'] = $fields['Field'];
}
echo "<pre>". print_r($field_names,true) . '</pre>';
?>

 

Ken

Change MadTechie's code to:

<?php
$field_names = array();
$cols = mysql_query("SHOW COLUMNS FROM `map`");
while($fields = mysql_fetch_assoc($cols))
{
if(substr($fields['Field'],0,4) == "mem_")
	$field_names['Field'] = $fields['Field'];
}
echo "<pre>". print_r($field_names,true) . '</pre>';
?>

 

Ken

 

I seem to be going backwards here. Now the code just outputs:

 

Array

(

    [Field] => mem_suppliers

)

 

So it's displaying one of the 2 column names in the database (i.e., mem_suppliers).

 

Ryan

Sorry, I wasn't thinking...

 

<?php
$field_names = array();
$cols = mysql_query("SHOW COLUMNS FROM `map`");
while($fields = mysql_fetch_assoc($cols))
{
if(substr($fields['Field'],0,4) == "mem_")
	$field_names[] = $fields['Field'];
}
echo "<pre>". print_r($field_names,true) . '</pre>';
?>

 

Ken

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.