简体   繁体   English

将关联数组中的单个键编码为 base64

[英]Encoding a single key in associative array to base64

I am trying to retrieve user data from a SQL table where one of the columns is blob_medium.我试图从其中一列是 blob_medium 的 SQL 表中检索用户数据。 I run the SQL query properly and get the data in the php script.我正确运行 SQL 查询并在 php 脚本中获取数据。

if(mysqli_num_rows($result)){
    while($row=mysqli_fetch_assoc($result)){
        $result_array['user_data'][]=$row;
    }
}

Now, to json_encode this data, I need to encode the data of user_pic column to base 64. For that I am trying this.现在,要对这些数据进行 json_encode,我需要将 user_pic 列的数据编码为 base 64。为此,我正在尝试这样做。 But, it seems I am doing something wrong.但是,似乎我做错了什么。 Any kind of help would be appreciated.任何形式的帮助将不胜感激。

foreach($result_array as $key){
      foreach($key as $key2){
            //print_r(base64_encode($key2['user_pic']).'<br/>'.'<br/>');
            $key2['user_pic'] = base64_encode($key['user_pic']);
           //print_r(($key['user_pic']).'<br/>'.'<br/>');
      }
}

When I uncomment the print_r statements my data is printed in base64 format but the data of the assoc array is not changing.当我取消对 print_r 语句的注释时,我的数据以 base64 格式打印,但 assoc 数组的数据没有改变。

That's because the array's $key and $keys in the for loop are copies.那是因为在 for 循环中数组的$key$keys是副本。 If you want them to modify the original you can either do it by specifying them to be references, not copies:如果您希望他们修改原件,您可以通过将它们指定为参考而不是副本来实现:

 foreach($result_array['user_data'] as &$key){
        $key['user_pic'] = base64_encode($key['user_pic']);
  }

Or by explicit index into the original:或者通过显式索引到原始:

 foreach($result_array['user_data']  as $index => $key){
        $result_array['user_data'][$index] ['user_pic'] = base64_encode($key['user_pic']);
 }

That's because you're changing the $key2 array.那是因为您正在更改$key2数组。 A temporary value created by your foreach loop.由您的foreach循环创建的临时值。 I myself would recommend using a for loop in this specific situation, because I was told to never use a loop within a loop if I can prevent it, and it makes things a lot easier to read:我自己会建议在这种特定情况下使用for循环,因为有人告诉我,如果可以防止的话,永远不要在循环中使用循环,并且它使事情更容易阅读:

for($i=0; $i < count($result_array['user_data']); $i++){
 $encodedUserPic = base64_encode($result_array['user_data'][$i]['user_pic']);
 $result_array['user_data'][$i]['user_pic'] = $encodedUserPic;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM