将值数字键转换为字符串php?

时间:2017-03-30 12:23:59

标签: php

这是我的代码:

 foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$key.'_'.md5(uniqid(rand(), true)).'.png';

    }

键值递增,我想将键号更改为如下字符串:

if $key=1 i want $key=white
if $key=2 i want $key=black

6 个答案:

答案 0 :(得分:0)

@ psppro26简单试试如下概念:

<?php
$color = array(1 => "white", 2 =>"black", 3 => "grey");
foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$color[$key].'_'.md5(uniqid(rand(), true)).'.png';

}

答案 1 :(得分:0)

最简单的解决方案就是那样

/* here you declare what should be swap to what, it can be in order, or you can index them manually */
$arrayToSwap = [
    1 => 'white',
    2 => 'black'
 ];
/* Here you change keys for future use */
$newArray = []
foreach ($urlImages as $key => $uu) {
    $newArray[$arrayToSwap[$key]] = $u;
}

答案 2 :(得分:0)

我会使用switch案例:

 foreach($urlImages as $key => $u){
    $type = 'default';

    switch ($key) {
      case 1:
        $type = 'white';
        break;
      case 2:
        $type = 'black';
        break;
    }

    $nameImg = $id_product.'_'.$type.'_'.md5(uniqid(rand(), true)).'.png';
 }

答案 3 :(得分:0)

$keyNameMap = [
   1=>'white',
   2=>'black'
];

// some codes
foreach ($urlImages as $key => $name) {
    $nameImg = $id_product.'_'.$keyNameMap[$key].'_'.md5(uniqid(rand(), true)).'.png';
    // come codes
}

答案 4 :(得分:0)

试试这个

if($contents!=='ok'){
    $response = $client->Request("POST", $url, [
        'handler'  => $stack,
        'headers'=>$headers,
        'form_params'=>$body
    ]);
    $contents = (string) $response->getBody();
}

first print_r Array([0] =&gt; photo1 [1] =&gt; photo2 [2] =&gt; photo3 [3] =&gt; photo4)

第二个print_r将返回Array([white] =&gt; photo1 [black] =&gt; photo2 [blue] =&gt; photo3 [pink] =&gt; photo4)

答案 5 :(得分:-1)

如果选择只有少数

,您可以使用比较运算符
$result = ($value == $condition?)valTrue : valFalse;

这个示例为您的案例1为白色,2为黑色,3为灰色。

 <?php
        $urlImages = array(  "1" => "test.png","2" => "test2.png", "3" => "test3.png");
        foreach($urlImages as $key => $u){
          $nameImg[] = $id_product.'_'.($key == 1?'white':($key == 2?'black':'grey')).'_'.md5(uniqid(rand(0,1000), true)).'.png';
        }
        print_r($nameImg);
        ?>

/ 结果 /

Array
(
    [0] => _white_6c4f456490be5893166478b2d35912ad.png
    [1] => _black_eb4c071837bf74ce6b9c1c445ff230f7.png
    [2] => _grey_80615be519a0d7db22a8241dc365acb9.png
)