开发者

Find one string and get related values

I have several strings, how can I search the first value and get other values from it?

开发者_运维百科

print_r or ?:

Array( [0] => Title,11,11 [1] => Would,22,22 [2] => Post,55,55 [3] => Ask,66,66 )

like:

If send for this array value Title and getting values Title,11,11

Or send Would getting values Would,22,22

Or send Post getting values Post,55,55

Or send Ask getting values Ask,66,66

How can do it?


Loop over the array with foreach and match the value with strpos.


suppose:

$arr = Array( [0] => Title,11,11 [1] => Would,22,22 [2] => Post,55,55 [3] => Ask,66,66 )
$string = 'Would'; 

then

//Call the function with the search value in $string and the actual array
$required_arr[$string] = search_my_array($string, $arr);

function($str , $array)
{
    //Trace the complete array
    for($i = 0; $i<count($array); $i++)
    {  
        //Break the array using explode function based on ','
        $arr_values[$i] = explode(',',$array[i])
        if($str == $arr_values[$i][0]) // Match the First String with the required string
        {
            //On match return the array with the values contained in it
            return array($arr_values[$i][1], $arr_values[$i][2]);
        }
    }
}

Now

$required_arr['Would']    // will hold Array([0] => 22 [1] => 22)


Write a function to search the array. This should work well enough

<?php
  // test array
  $arr = array('Title,11,11','Would,22,22','Post,55,55','Ask,66,66');
  // define search function that you pass an array and a search string to
  function search($needle,$haystack){
    // loop over each passed in array element
    foreach($haystack as $v){
      // if there is a match at the first position
      if(strpos($v,$needle) === 0)
        // return the current array element
        return $v;
    }
    // otherwise retur false if not found
    return false;
  }
  // test the function
  echo search("Would",$arr);
?>


are the indices important ? why not ..

$arr = array(
  'Title' => array(11, 11),
  'Would' => array(22, 22),
  'Post' => array(55, 55),
  'Ask' => array(66,66)
);

$send = "Title";     // for example
$result = $arr[$send];


How about using something like, so you don't loop trough entire array:

$array = array( "Title,11,11", "Would,22,22", "Post,55,55", "Ask,66,66" );
$key = my_array_search('Would', $array);
$getvalues = explode(",", $array[$key]);

function my_array_search($needle = null, $haystack_array = null, $skip = 0)
{
    if($needle == null || $haystack_array == null)
        die('$needle and $haystack_array are mandatory for function my_array_search()');
    foreach($haystack_array as $key => $eval)
    {
        if($skip != 0)$eval = substr($eval, $skip);
        if(stristr($eval, $needle) !== false) return $key;
    }
    return false;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜