从数组转换值? PHP

时间:2012-05-02 11:50:25

标签: php arrays

我想在插入MySQL之前从数组转换值。我使用了以下代码,但它仅适用于某些情况(2_AAA,2_AAA_1)bun不适用于案例(2_AA_B,2_AA_B_1,AA_AB)。

$vars = array('val' => '2_AAA',
              'val' => '2_AAA_1',
              'val' => '2_AA_B',
              'val' => '2_AA_B_1',
              'val' => 'AA_AB');

foreach ($vars as $v):
    $vArr = explode('_', $v['val']);

    if (is_numeric($vArr[0]) && count($vArr[0])) {
        $vid = $vArr[0];
        $name = trim($vArr[1]);
        $name_real = $var;
    } else {
        $vid = 0;
        $name = $v['val'];
        $name_real = $v['val'];
    }

    echo "VID -->" . $vid . "\n";
    echo "NAME -->" . $vArr[0] . "\n";
    echo "NAME_REAL -->" . $name_real . "\n";

endforeach;

从这个数组我想得到以下结果

//VID -->2
//NAME -->AAA
//NAME_REAL -->2_AAA

//VID -->2
//NAME -->AAA
//NAME_REAL -->2_AAA_1

//VID -->2
//NAME -->AA_B
//NAME_REAL -->2_AA_B

//VID -->2
//NAME -->AA_B
//NAME_REAL -->2_AA_B_1

//VID -->0
//NAME -->AA_AB
//NAME_REAL -->AA_AB

如果在名称之前不能加前缀,则VID为0。

我该怎么做?

提前致谢!

3 个答案:

答案 0 :(得分:0)

这个怎么样?以下代码给出了您似乎期待的输出。

<?php

$vars = array(
    array( 'val' => '2_AAA' ),
    array( 'val' => '2_AAA_1' ),
    array( 'val' => '2_AA_B' ),
    array( 'val' => '2_AA_B_1' ),
    array( 'val' => 'AA_AB' )
);

foreach ($vars as $v) {
    $vArr = explode('_', $v['val']);

    if( is_numeric( $vArr[0] ) ) {
        $vid = $vArr[0];
        $name = $vArr[1];
        $name_real = $v['val'];
    }
    else {
        $vid = 0;
        $name = $v['val'];
        $name_real = $v['val'];
    }

    echo "VID --> $vid\n";
    echo "NAME --> $name\n";
    echo "NAME_REAL --> $name_real\n";
    echo "\n";

}

答案 1 :(得分:0)

尝试这样做..这不是一个解决方案,但这会让你大致了解如何做到这一点: -

$vars = array('0' => '2_AAA',
              '1' => '2_AAA_1',
              '2' => '2_AA_B',
              '3' => '2_AA_B_1',
              '4' => 'AA_AB');

foreach ($vars as $v):
$i=0;
    $vArr = explode('_', $v);
print_r($vArr);echo "</br>";
    if (is_numeric($vArr[$i]) && count($vArr[0])) {
        $vid = $vArr[$i];
        $name = trim($vArr[$i+1]);
        $name_real = $var;
    } else {

    }

    echo "VID -->" .$vid ; echo "</br>";
    echo "NAME -->" . $vArr[$i+1];echo "</br>";
    echo "NAME_REAL -->" . $name_real;echo "</br>";

endforeach;

答案 2 :(得分:0)

$vars = array('2_AAA','2_AAA_1','2_AA_B','2_AA_B_1','AA_AB');

foreach ($vars as $v):
    $vArr = explode('_', $v);
    $name = '';
    for($i=0; $i<sizeof($vArr); $i++){
            if(is_numeric($vArr[0]))
        $vid = $vArr[0];
    else
        $vid = 0;

    if(!is_numeric($vArr[$i])){
        if($name)
            $name .= '_'.$vArr[$i]; 
        else
            $name = $vArr[$i];
    }
    $name_real = $v;
}

echo '<br/>------------------------------------------------------<br/>';
echo "VID -->" . $vid . "<br/>";
echo "NAME -->" . $name . "<br/>";
echo "NAME_REAL -->" . $name_real . "<br/>";

endforeach;