dpo15099
2016-10-16 17:43 阅读 26
已采纳

如何使用字符串中的键获取数组的值

I have an array with some keys and I want to get the array values according to the array keys where the keys are in a string.

Example:

$arr = array(
        "COV" => "Comilla Victorians",
        "RK"  => "Rajshaji Kings"
    );

$str = "COV-RK";

Now I want to show Comilla Victorians VS Rajshaji Kings.

I can do it using some custom looping, But I need some smart coding here and looks your attention. I think there are some ways to make it with array functions that I don't know.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dtrn74832 dtrn74832 2016-10-16 17:55

    You could do something like:

    echo implode(' VS ', array_map(function($v) use ($arr) { return $arr[$v]; }, explode('-', $str)));
    

    So explode the string, map the resulting array, returning the value of the matching key in $arr, then just implode it.

    点赞 评论 复制链接分享
  • duanjiwang2927 duanjiwang2927 2016-10-16 17:48

    You could try this:-

    <?php
    
    $arr = array(
        "COV" => "Comilla Victorians",
        "RK"  => "Rajshaji Kings"
    );
    
    $str = "COV-RK";
    
    $values = explode("-", $str); // explode string to get keys actually
    
    echo $arr[$values[0]] . " VS " . $arr[$values[1]]; // print desired output
    
    点赞 评论 复制链接分享

相关推荐