我有一个名为"manufacturer"的数据库字段,其中一些数字用管道分隔。
例如1572|906|1573
我想选择第一个数字并将其存储为变量。
这是我可悲的努力,但没有取得成功。
$thisproductmansarray=array(); //declare the array
$thisproductmans=$myfield["manufacturer"]; //For page title / breadcrumb etc
$xxarray=implode("|", $thisproductmans[$key]);
foreach($thisproductmans as $key=>$val){
$thisproductmansarray[]=$xxarray++;
echo $thisproductmansarray[0];
}
有人能给我一个指针吗。感谢
$xxarray=explode("|", $thisproductmans);
echo $xxarray[0]; // this should be what you want
$data = explode('|', $the-variable-where-the-data-is-in);
echo $data[0];
将显示第一个数字。在您的示例"1572"中。
$items = explode("|", $fieldfromdb);
$val = $items[0];
<?php
$str = '1572|906|1573';
$first_num = current(explode("|",$str));
echo $first_num;
看起来爆炸才是你真正想要的。explode()获取一个分隔字符串并转换为一个部分数组。
$thisproductmans=$myfield["manufacturer"]; //For page title / breadcrumb etc
$xxarray=explode("|", $thisproductmans[$key]);
if(count($xxarray) > 1)
echo $xxarray[0];
如果您需要更多信息,请查看explode()的手册页。
您可以在不使用数组的情况下直接获得第一个数字:-
$var = "1572|906|1573";
list($first) = explode('|', $var);
$first
现在将=1572。
看到它工作和list()
。
如果你有PHP V>=5.4,你可以这样做:-
$var = "1572|906|1573";
$first = explode('|', $var)[0];
var_dump($first);
让它发挥作用。
在代码中使用它的示例
<?php
$var = "1572|906|1573";
$array1 = explode("|", $var);
$first_value = $array1[0];
echo $first_value; // Output here is 1572
?>