Jump to content

How to extract information from an existing Array to a new Array?


pescatore

Recommended Posts

Hi, I am very new to PHP and apologies if this question has already been answered in another thread.

 

I am trying to extract the information from one array into another when some search criteria is matched.

 

Here is an example array ($original):

Array ( [ 1234567 ] => Array ( [name] => john ) [ 3456 ] => Array ( [name] => johnny ) [ 45673 ] => Array ( [name] => james ) [ 987 ] => Array ( [name] => jamie ) [ 5628721 ] => Array ( [name] => Simon ))

 

So if I searched for the string john, jo, joh then the new array ($filtered) should be as follows:

Array ( [ 1234567 ] => Array ( [name] => john ) [ 3456 ] => Array ( [name] => johnny ))

 

I was trying to do this using array_search & preg_match but have been struggling.

 

Any help would be much appreciated!

 

array_search doesn't work on multidimensional arrays like you have. You'll have to loop over the outermost array first and then search on the inner one.

 

Try something like this:

$original = array(
    1234567 => array('name' => 'john'),
    3456 => array('name' => 'johnny'),
    45673 => array('name' => 'james'),
    987 => array('name' => 'jamie'),
    5628721 => array('name' => 'Simon'),
);

$filtered = array();

$search = 'jo';

foreach ($original as $index => $o) {
    if (stripos($o['name'], $search) !== false) {
        $filtered[$index] = $o;
    }
}

Use foreach loop + preg_match to match the beginning of each new array value and then put the results into a new array.

 

Like this; 


// Original array
$original = array(1234567  => array('name' => 'john' ) , 3456  => array ( 'name' => 'johnny' ), 1212 => array('name' => 'james'));
// Term to search for
$search = 'jo';
// New array to put the results in
$filtered = array();
// Looping through the $original array
// and if the $search value matches the 
// begining of the value string
// then append the results in the $fileted array
foreach ($original as $key => $value) {
	if(preg_match("/^$search/", $value['name'] )){
	$filtered[] =  $value['name'];
}
}
// Display the new array with the filtered results.
print_r($filtered);

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.