我有几个字符串,如何搜索第一个值并从中获取其他值?
print_r
或?
:
Array( [0] => Title,11,11 [1] => Would,22,22 [2] => Post,55,55 [3] => Ask,66,66 )
像:
如果发送此数组值Title
并获取值Title,11,11
或者发送Would
获取值Would,22,22
或者发送Post
获取值Post,55,55
或者发送Ask
获取值Ask,66,66
怎么办?
答案 0 :(得分:1)
答案 1 :(得分:1)
假设:
$arr = Array( [0] => Title,11,11 [1] => Would,22,22 [2] => Post,55,55 [3] => Ask,66,66 )
$string = 'Would';
然后
//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]);
}
}
}
现在
$required_arr['Would'] // will hold Array([0] => 22 [1] => 22)
答案 2 :(得分:1)
编写一个函数来搜索数组。这应该足够好了
<?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);
?>
答案 3 :(得分:0)
指数重要吗?为什么不..
$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];
答案 4 :(得分:0)
如何使用类似的东西,所以你不要遍历整个数组:
$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;
}