Reputation: 247
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
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
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
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
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