将数组键替换为值名称的一部分

时间:2015-07-07 12:03:20

标签: php arrays multidimensional-array

我有这种格式的数组

[0] => Array
        (
            [0] => FieldType: Text
            [1] => FieldName: Job title
            [2] => FieldFlags: 0
            [3] => FieldValue: ICT Manager
            [4] => FieldJustification: Left
        )

我怎样才能让它看起来像

[0] => Array
        (
            [FieldType: ] => Text
            [FieldName: ] => Job title
            [FieldFlags: ] => 0
            [FieldValue: ] => ICT Manager
            [FieldJustification: ] => Left
        )

3 个答案:

答案 0 :(得分:1)

尝试如下: -

    <?php

 $array = Array
    (
        0 => Array
        (
            0 => 'FieldType: Text',
            1 => 'FieldName: Job title',
            2 => 'FieldFlags: 0',
            3 => 'FieldValue: ICT Manager',
            4 => 'FieldJustification: Left'
        )
    );
$new_array = array();
$i  = 0;
foreach($array as $val){ // iterate through array
        foreach($val as $k=> $v){ //for each index one array is there so iterate that also
            $data = explode(':',$v); // explode the value by :
            $new_array[$i][$data[0].":"] = $data[1]; // assign first value as key and second value as value to the new array
        }
    $i++;
}
echo "<pre/>";print_r($new_array); //print new array
?>

输出: - https://eval.in/394135

答案 1 :(得分:0)

$result = array();
foreach ($input as $rows) {
    $output = array();
    foreach ($rows as $subRow) {
        $values = explode(':', $subRow);
        if (count($values) == 2) {
            $output[$values[0] . ':'] = trim($values[1]);
        }
    }
    $result[] = $output;
}

答案 2 :(得分:0)

$array = array(
    '0' => array(
        '0' => 'FieldType: Text',
        '1' => 'FieldName: Job title',
        '2' => 'FieldFlags: 0',
        '3' => 'FieldValue: ICT Manager',
        '4' => 'FieldJustification: Left'
    )
);

$nArray = array();
foreach($array as $k => $v){
    foreach($v as $key => $value){
        if(($pos = strpos($value, ':')) !== false){
            $nArray[$k][substr($value, 0, $pos + 1)] = trim(substr($value, $pos + 1));
        } else {
            $nArray[$k][] = $value;
        }
    }
}

echo '<pre>';
print_r($nArray);