从php中的数组获取值并爆炸
问题描述:
I have this the values of in my array as
$itsthere = (item1-0-100, item2-0-50, item3-0-70, item4-0-50, item5-0-100);
If the user enter the value item3
he has to get 70
which is present in array. I tried alot using explode but its not showing proper value. Can any one help me.
我的数组中的值为 p>
$ itsthere =(item1-0-100,item2-0-50,item3-0-70,item4-0-50,item5-0-100);
code> pre>
如果用户输入值 item3 code>,他必须得到 70 code>,它存在于数组中。 我尝试了很多使用爆炸但它没有显示正确的价值。 任何人都可以帮助我。 p>
div>
答
Try this :
$item = 'item3';
$itsthere = array('item1-0-100', 'item2-0-50', 'item3-0-70', 'item4-0-50', 'item5-0-100');
foreach($itsthere as $there)
{
$exp = explode('-',$there);
if($exp[0] == 'item3') {
echo $val = $exp[2];
};
}
答
Try with:
$itsthere = array(
'item1-0-100',
'item2-0-50',
'item3-0-70',
'item4-0-50',
'item5-0-100'
);
$search = 'item3';
$output = '';
foreach ( $itsthere as $value ) {
if ( strpos($search . '-', $value) === 0 ) {
$output = explode('-', $value)[2];
break;
}
}
答
When you say item3 are you refering to the third position or the item3 as array key? I think you can create a assoc array and make item names as key
$isthere = array('item1' => '0-100', 'item2' => '0-50' ,'item3' => '0-70', ....,);
echo $isthere['item3']; // This would give you the value.
If you only want to know if this key is in the array use array_key_exists.