MorganFreeFarm
MorganFreeFarm

Reputation: 3733

Array to string in array

This is my array, but some values are empty array and i want to convert them into empty strings, but i'm not sure how. Try some solutions, but "can't convert array to string".

array(1) {
      [0]=>
      array(32) {
        ["product_id"]=>
        string(2) "30"
        ["name"]=>
        string(12) "Canon EOS 5D"
        ["model"]=>
        string(9) "Product 3"
        ["sku"]=>
        array(0) {
        }
        ["upc"]=>
        array(0) {
        }
        ["ean"]=>
        array(0) {
        }
        ["jan"]=>
        array(0) {
        }
        ["manufacturer_id"]=>
        string(1) "9"
        ["tax_class_id"]=>
        string(1) "9"
        ["points"]=>
        string(1) "0"
        ["quantity"]=>
        string(1) "7"
        ["minimum"]=>
        string(1) "1"
        ["isbn"]=>
        array(0) {
        }
        ["mpn"]=>
        array(0) {
        }
        ["stock_status_id"]=>
        string(1) "6"
      }

But i want these:

["sku"]=>
        array(0) {
        }
        ["upc"]=>
        array(0) {
        }
        ["ean"]=>
        array(0) {
        }
        ["jan"]=>
        array(0) {
        }

to looks like this:

["sku"]=>
        string(0) ""
        ["upc"]=>
        string(0) ""
        ["ean"]=>
        string(0) ""
        ["jan"]=>
        string(0) ""

a.k.a empty string, not arrays. That's it. Maybe some check if is empty array to convert to string, i'm not sure. Thank u!

Upvotes: 0

Views: 93

Answers (3)

Dmitriy Suniaikin
Dmitriy Suniaikin

Reputation: 118

    foreach ($products['shopproduct'] as $product) {
        foreach ($product as $k => $v) {
            if (empty($v)) {
                $product[$k] = '';
            }
        }
    }
    echo "<pre>";
    var_dump($products['shopproduct']);

The problem you're working with copy ($product) of an array in foreach. You can use ampersand for reference like

foreach ($products['shopproduct'] as &$product) {
...

or

    foreach ($products['shopproduct'] as $j => $product) {
        foreach ($product as $k => $v) {
            if (empty($v)) {
                $products['shopproduct'][$j][$k] = '';
            }
        }
    }

Upvotes: 1

Bhunesh  Satpada
Bhunesh Satpada

Reputation: 810

Use array_map. Check below code:

$array2 = array_map(function($value) {
   return count($value) == 0 ? "" : $value;
}, $array);

Upvotes: 1

Loko
Loko

Reputation: 6679

Just replace it with an empty string when the value is empty.

foreach($array as $k=>$v){
    if(empty($v)){
        $array[$k]='';
    }
}

Upvotes: 1

Related Questions