Question

I have a an multidimensional array which I would like to json_encode but before I do so I need to base64_encode the arrays corresponding to the products images.

e.g

var_dump($products_results) // outputs

array(18) {
     [0]=>
        array(70) {
               ["product_id"]=> string(4) "9087"
               ["make"]=> string(6) "shinox"
               ["color"]=> string(3) "red"
               ["country"]=> string(3) "usa"
               ["image"]=> string(6201) "����ExifII*��Ducky��Adobed����....."
               ["image_front"]=> string(5201) "��������....."
               ["image_back"]=> string(5201) "��������....."

              .....
     [1]=>
        array(70) {
               ["product_id"]=> string(4) "8999"
               ["make"]=> string(6) "shinox"
               ["color"]=> string(3) "black"
               ["image"]=> string(6201) "����ExifII*��Ducky��Adobed����....."
               ["image_front"]=> string(5201) "��������....."
               ["image_back"]=> string(5201) "��������....."

ect....

Here each array represents a product in my sql database, where images are stored as binary data instead of a URL path in order to allow some offline functionality... This the first time I try to store images, I created VARBINARY columns for images as I read on many posts on this forum and now I need to base64_encode these images before sending it client side as an object.

My question is how can I loop through each products array to base64_encode the three arrays whose key are image , image_front and image_back related to the images.

$JSON_array = array();

$JSON_array["Products"] = $products_results; // contains the 18 arrays above with images encoded

$JSON_array["specifications"] = $specs_results // some other stuff to send along no need changes

print json_encode($JSON_array);
Was it helpful?

Solution

The trick is keeping track of the array index values so you can update the original.

foreach ($JSON_array['Products'] as $productIndex => $product)
{
   $JSON_array['Products'][$productIndex]['image'] = base64_encode($product['image']);
   $JSON_array['Products'][$productIndex]['image_front'] = base64_encode($product['image_front']); 
   $JSON_array['Products'][$productIndex]['image_back'] = base64_encode($product['image_back']);      
}

This updates the original array outside of the loop with base64_encode values. Then you should be able to easily json_encode() that array.

$output = json_encode($JSON_array);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top