动态获取PHP中的最后一个公共数组值

时间:2018-05-21 12:46:07

标签: php arrays

我有原始数组,如下所示

$orginal_arra = Array(
    [0] => 53_0.1,
    [1] => 53_0.3,
    [2] => 54_0.2,
    [3] => 54_0.1,    
    [4] => 54_0.1,
    [5] => 54_0.19,
    [6] => 56_0.19,
    [7] => 56_0.50
);

以上数组可以通过" _"分离

foreach($orginal_arra as $part) {
    if($part){
        $arr_parts = explode("_",$part);
        $arr1[] = $arr_parts[0];
        $arr2[] = $arr_parts[1];
    }
}

施法后的$ arr1结果

Array (
    [0] => 53,
    [1] => 53,
    [2] => 54,
    [3] => 54,
    [4] => 54,
    [5] => 54,
    [6] => 56,
    [7] => 56
)

施法后的$ arr2结果

Array (
    [0] => 0.1,
    [1] => 0.3,
    [2] => 0.2,
    [3] => 0.1,
    [4] => 0.1,
    [5] => 0.19,
    [6] => 0.19,
    [7] => 0.50
)

我希望通过将$ arr1和$ arr2组合为

来返回数组
$array = Array(
    [0] => 53_0.3,
    [1] => 54_0.19,
    [2] => 56_0.50
);

有没有办法使用PHP Arrays获得上面的结果。

3 个答案:

答案 0 :(得分:4)

您可以使用array_values将数组分组为关联数组。使用array_values将关联数组转换为简单数组。

$orginal_arra = array(
    '53_0.1',
    '53_0.3',
    '54_0.2',
    '54_0.1',    
    '54_0.1',
    '54_0.19',
    '56_0.19',
    '56_0.50'
);

$result = array_values(array_reduce($orginal_arra, function($c,$v){
    $key = explode('_', $v);   //explode the value
    $c[$key[0]] = $v;          //Use the first element of the explode value as a key and just overide the value
    return $c;
}, array()));


echo "<pre>";
print_r( $result );
echo "</pre>";

这将导致:

Array
(
    [0] => 53_0.3
    [1] => 54_0.19
    [2] => 56_0.50
)

答案 1 :(得分:1)

login_manager.refresh_view = "accounts.reauthenticate" login_manager.needs_refresh_message = ( u"To protect your account, please reauthenticate to access this page." ) login_manager.needs_refresh_message_category = "info" 是完美的临时密钥生成器。每个重复键将覆盖以前的值。循环结束后,只需使用 from datetime import timedelta from flask import session, app #make the session permanent and set expiry period session.permanent = True app.permanent_session_lifetime = timedelta(minutes=5) #everytime a user visits, modify the session so that you know they are still active @app.before_request def func(): session.modified = True 重新索引结果数组。干净简单。

代码:(Demo

strstr()

输出:

array_values()

答案 2 :(得分:0)

如果要合并$array2 <?php $array1= array( "0" => 53, "1" => 53, "2" => 54, "3" => 54, "4" => 54, "5" => 54, "6" => 56, "7" => 56 ); $array2 = array ( "0" => 0.1, "1" => 0.3, "2" => 0.2, "3" => 0.1, "4" => 0.1, "5" => 0.19, "6" => 0.19, "7" => 0.50 ); $array1 = array_reverse($array1, true); $array1 = array_unique($array1); foreach($array1 as $key=>$val){ $array1[$key] = $val."_".number_format((float)$array2[$key], 2, '.', ''); } print_r(array_reverse($array1));

,可以执行此操作
Array
(
    [0] => 53_0.30,
    [1] => 54_0.19,
    [2] => 56_0.50
)

输出:

name            type          data
----------------------------------
update_url      REG_SZ        https://clients2.google.com/service/update2/crx