创建数组并获取第一个值

时间:2013-12-11 17:46:38

标签: php arrays

我有一个名为'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];
}

任何人都可以给我一个指针。 感谢

7 个答案:

答案 0 :(得分:2)

$xxarray=explode("|", $thisproductmans);
echo $xxarray[0]; // this should be what you want

答案 1 :(得分:2)

$data = explode('|', $the-variable-where-the-data-is-in);
echo $data[0];

将显示第一个数字。在你的例子“1572”。

答案 2 :(得分:1)

$items = explode("|", $fieldfromdb);
$val = $items[0];

答案 3 :(得分:1)

<?php
$str = '1572|906|1573';
$first_num = current(explode("|",$str));
echo $first_num;

答案 4 :(得分:0)

看起来爆炸是你真正想要的。 explode()接受一个分隔的字符串并转换为一个部分数组。

$thisproductmans=$myfield["manufacturer"]; //For page title / breadcrumb etc
$xxarray=explode("|", $thisproductmans[$key]);
if(count($xxarray) > 1)
    echo $xxarray[0];

如果您需要更多信息,请查看man page以了解爆炸()。

答案 5 :(得分:0)

您可以直接获取第一个数字而不使用数组: -

$var = "1572|906|1573";
list($first) = explode('|', $var);

$first现在= 1572。

See workinglist()

如果你有PHP V&gt; = 5.4,你可以这样做: -

$var = "1572|906|1573";
$first = explode('|', $var)[0];
var_dump($first);

See it work

答案 6 :(得分:-1)

您在代码中使用它的示例

<?php
$var = "1572|906|1573";

$array1 = explode("|", $var);

$first_value = $array1[0];
echo $first_value;  // Output here is 1572

?>
相关问题