0

我有一个名为$matches下面的数组,你可以看到一个

的结果 print_r(array_filter($matches));

Array ( 
[0] => Array ( 
    [0] => Age: 
    [1] => 22 Years 
    [2] => Ethnicity: 
    [3] => Caucasian 
    [4] => Location: 
    [5] => London, United Kingdom

结果 var_dump($matches);

array(1) { 
[0]=> array(66) { 
    [0]=> string(202) " Age: " 
    [1]=> string(157) " 22 Years " 
    [2]=> string(196) " Ethnicity: " 
    [3]=> string(146) " Caucasian " 
    [4]=> string(195) " Location: " 
    [5]=> string(175) " London, United Kingdom "

所以这里的结构是 Key -> Value, Key -> Value,..

正如您注意到的所有键(值名称)都以:

我想要的结果

echo $age;         // Should result: 22 Years
echo $ethnicity;   // Should result: Caucasian
echo $location;    // Should result: London, United Kingdom

如何将数组编号 0、2、4 作为值名称?

并且热设置数组编号 1,2,5 作为他们的结果?

4

1 回答 1

1

如果您真的只想重新映射并且事情会发生变化,请尝试:

function remap_alternating(array $values) {
    $remapped = array();
    for($i = 0; $i < count($values) - 1; $i += 2) {
        $remapped[trim($values[$i], ": ")] = trim($values[$i + 1], " ");
    }
    return $remapped;
}

然后你可以使用

$mapped = remap_alternating($matches[0]);

foreach($mapped as $key => $val) {
    echo "<p>$key = $val</p>";
}

我将 $matches 设置为此:

$matches = array(
    array ( " Age: ", " 22 Years ", " Ethnicity: ", " Caucasian ", " Location: ", " London, United Kingdom " )
);

它打印:

年龄 = 22 岁

种族=高加索人

地点 = 英国伦敦

于 2013-11-07T02:30:12.490 回答