将数组元素与"在两端标记

时间:2017-07-30 00:29:15

标签: php

我需要将两个或多个数组元素组合在一个双引号内... 例:   - 之前 -

UIView.transition(with: thisButton, duration: 0.2, options: [.transitionFlipFromTop,.repeat], animations: {
    thisButton.setImage(myButtonImage, for: .normal)
}, completion: nil)

- 后 -

[
 "Foo1",
 "\"Foo2",
 "Foo3",
 "Foo4\"",
 "Foo5"
]

2 个答案:

答案 0 :(得分:0)

function combine_inside_quotation($array)
{
    if(!is_array($array) || 0 === ($array_lenght = count($array))) {
        return [];
    }

    $i = 0;
    $j = 0;
    $output = [];
    $inside_quote = false;

    while($i < $array_lenght) {
        if (false === $inside_quote && '"' === $array[$i][0]) {
            $inside_quote = true;
            $output[$j] = $array[$i];
        }else if (true === $inside_quote && '"' === $array[$i][strlen($array[$i]) - 1]) {
            $inside_quote = false;
            $output[$j] .= ' ' . $array[$i];
            $j++;
        }else if (true === $inside_quote && '"' !== $array[$i][0] && '"' !== $array[$i][strlen($array[$i]) - 1]) {
            $output[$j] .= ' ' . $array[$i];
        } else {
            $inside_quote = false;
            $output[$j] = $array[$i];
            $j++;
        }
        $i++;
    }


    return $output;
}

尝试此功能,它会提供您提到的输出。

Live Demo

答案 1 :(得分:0)

下面,$source$result分别是来源和结果。我会使用array_reduce()

$result = array_reduce($source, function($acc,$i) {
    static $append = false; // static so value is remembered between iterations

    if($append) $acc[count($acc)-1] .= " $i"; // Append to the last element
    else $acc[] = $i; // Add a new element

    // Set $append=true if item starts with ", $append=false if item ends with "
    if(strpos($i,'"') === 0) $append = true;
    elseif (strpos($i,'"') === strlen($i)-1) $append = false;

    return $acc; // Value to be inserted as the $acc param in next iteration
}, []);

Live demo

相关问题