从数组中删除特定字符串并将其指定为其键

时间:2017-03-14 15:16:57

标签: php arrays multidimensional-array

我想在:之前取出所有字符串并将其指定为相应的键

这是我的阵列:

Array
(
    [0] => Array
        (
            [0] => FileName:index.php
            [1] => Description:Display the home page
            [2] => Version:1.1
            [3] => Author: Developer
            [4] => Author URI: https://developer.blogspot.com
        )

)

我想要这种格式:

Array
    (
        [0] => Array
            (
                ['FileName'] => index.php
                ['Description'] => Display the home page
                ['Version'] => 1.1
                ['Author'] => Developer
                ['Author URI'] => https://developer.blogspot.com
            )

    )

感谢任何人的帮助。

2 个答案:

答案 0 :(得分:0)

试试这个。

<?php
$arr = array( "FileName:index.php", 
             "Description:Display the home page",     
             "Version:1.1", 
              "Author: Developer", 
            "Author URI: https://developer.blogspot.com"
        );
$finalArr = [];
for($i=0;$i<count($arr);$i++) {
   $newKey = explode(':',$arr[$i]);
   $finalArr[$newKey[0]] = $newKey[1];
}

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


Array
(
    [FileName] => index.php
    [Description] => Display the home page
    [Version] => 1.1
    [Author] =>  Developer
    [Author URI] =>  https
)

答案 1 :(得分:0)

您可以尝试使用此功能:

<?php

$array = Array
(
    Array
        (
            0 => 'FileName:index.php',
            1 => 'Description:Display the home page',
            2 => 'Version:1.1',
            3 => 'Author: Developer',
            4 => 'Author URI: https://developer.blogspot.com'
        )
);

$array = process_array($array);
var_dump($array);

function process_array(array $array) {
    $datas = array();
    foreach($array as $key => $value) {
        foreach($value as $text) {
            $parts = explode(':', $text);
            $newKey = array_shift($parts);
            $datas[$key][$newKey] = implode(':', $parts);
        }
    }

    return $datas;
}