search

Home  >  Q&A  >  body text

php - How to use foreach and for to process the following array into the string below the array?

$arr = array(
                'id' => 'ID',
                'staff_name' => '昵称',
                'staff_real '=> '真实姓名',
            );

$strKey = 'id,staff_name,staff_real';
$strValue = 'ID,昵称,真实姓名';

As above, $arrHow to output the key name into a string and the key value into a string?
I heard that it can be achieved using the arraykeys and arraryvalue functions, but I don’t know how to write them. I also want to know how to use foreach and forHow to deal with it.
Want to let you know, thank you.

欧阳克欧阳克2717 days ago1060

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-06-12 09:23:57

    $strKey = implode(',', array_keys($arr));
    $strValue = implode(',', array_values($arr));

    reply
    0
  • typecho

    typecho2017-06-12 09:23:57

    echo implode(',', array_keys($arr));
    echo implode(',', $arr);

    reply
    0
  • 代言

    代言2017-06-12 09:23:57

    It’s actually very simple. The author must not know much about PHP! !

    1. The first step is to use array_keys() to get all the keys from the array to form a new array.

    2. The second step is to convert the two arrays into strings through implode().

    Next, let’s talk about the solution to the foreach loop that the poster wants to know:

    1. The first step is to concatenate strings in a loop.

    2. The second step is to remove the comma at the end of the string.

    The code is as follows:

    $arr = array(
        'id' => 'ID',
        'staff_name' => '昵称',
        'staff_real '=> '真实姓名'
      );
    
      $keystr = '';
      $valstr = '';
      foreach($arr as $key => $val) {
        $keystr .= $key.',';
        $valstr .= $val.',';
      }
      $keystr = trim($keystr, ',');
      $valstr = trim($valstr, ',');
      echo $keystr;

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-06-12 09:23:57

    https://www.bytelang.com/o/s/...

    reply
    0
  • Cancelreply