user3729576
user3729576

Reputation: 247

Create a string from an array

I have an array:

array(
 array('w' => '100', 'h'=>'100'),
 array('w' => '200', 'h'=>'200'),
 array('w' => '300', 'h'=>'300')
)

I ned to create a string from this array that looks like:

[100, 100], [200, 200], [300, 300]

I've looked at:

array_values()

I use it by looping through each array to remove the key, but what would be the best way to make the entire string, with square brackets?

Upvotes: 0

Views: 79

Answers (5)

TBI
TBI

Reputation: 2809

$array=array(
 array('w' => 100, 'h'=>100),
 array('w' => 200, 'h'=>200),
 array('w' => 300, 'h'=>300)
);
$str='';
foreach ($array as $key=>$val) {
    $str .= '['.$val['w'].','.$val['h'].'],';
}
$str = substr($str,0,-1);
echo $str;

Upvotes: 0

user3778553
user3778553

Reputation:

You just need to use json_encode():

$values = array(
     array('w' => '100', 'h'=>'100'),
     array('w' => '200', 'h'=>'200'),
     array('w' => '300', 'h'=>'300'),
);

$new_values = array();
foreach ($values as $value) {
    // put cast int @Tash:
    $new_values[] = json_encode(array((int)$value['w'], (int)$value['h']));
}

echo implode(',', $new_values); // [100,100],[200,200],[300,300]

Upvotes: 1

Njuguna Mureithi
Njuguna Mureithi

Reputation: 3856

That is Json.

Try this, even though not so clean.

<?php
$ace=array(
 array('w' => 100, 'h'=>100),
 array('w' => 200, 'h'=>200),
 array('w' => 300, 'h'=>300)
);
$json="";
foreach($ace as $key=>$value){
    $json.= json_encode(array($value['w'],$value['h'])) . ",";
}
echo substr($json,0,-1);//remove last comma

Upvotes: 0

hongchuyen
hongchuyen

Reputation: 31

$tmp = array(
    array('w' => 100, 'h' => 100),
    array('w' => 200, 'h' => 200),
    array('w' => 300, 'h' => 300)
);
$str = '';
foreach ($tmp as $i => $value) {
    if ($i == 0)
        $str = '[' . implode(',', $value) . ']';
    else
        $str.= ', [' . implode(',', $value) . ']';
}
var_dump($str);

Upvotes: 0

Fluffeh
Fluffeh

Reputation: 33512

You can use implode to format along with some basic string concat like this:

$string='';
foreach($mainArray as $v)
{
    $string.='['.(implode(',',$v)).'],';
}
$string=substr($string,0,-1);

The last bit wioll remove the trailing comma from the foreach statement.

Upvotes: 2

Related Questions