json encode return as objects instead array - php

I have already read this question and doesn't answer my issue.
I have an Array like this:
Array
(
[0] => Array
(
[COM] => 10659.68
)
[1] => Array
(
[MCD] => 1219.09
)
[2] => Array
(
[MCR] => 77047.65
)
)
And when I make a json_encode() it return this;
[{"COM":10659.68},{"MCD":1219.09},{"MCR":77047.65}]
What I need is get the data in this way:
[["COM":10659.68],["MCD":1219.09],["MCR":77047.65]]
Any idea how can I achieve this

Even though that's not a valid JSON, you can replace the { with [
echo str_replace(array('{','}'),array('[',']'),json_encode($your_array));
Depending on the content you might need a more complex replacement with regular expressions.

More complex solution:
function toJson($arr){
$return = array();
foreach($arr as $k => $v){
if(is_array($v)) $return[] = toJson($v);
else $return[] = sprintf('"%s":%s', $k, $v);
}
return sprintf('[%s]', implode(',', $return));
}
Test:
$input = array(
array('COM' => '10659.68'),
array('MCD' => '1219.09'),
array('MCR' => '77047.65'),
);
var_dump(toJson($input));
string(51) "[["COM":10659.68],["MCD":1219.09],["MCR":77047.65]]"

Related

PHP Puttin values of array into multidimensional array

Hello I want to put values of single array into a multidimensional array with each value on a n+1
This is my array $structures
Array
(
[0] => S
[1] => S.1
[2] => S-VLA-S
[3] => SB
[4] => SB50
)
What I want for output is this
Array
(
[S] => Array(
[S.1] => Array (
[S-VLA-S] => Array (
[SB] => Array (
[SB50] => Array(
'more_attributes' => true
)
)
)
)
)
)
This is what I have tried so far
$structures = explode("\\", $row['structuurCode']);
foreach($structures as $index => $structure) {
$result[$structure][$structure[$index+1]] = $row['structuurCode'];
}
The values of the array is a tree structure that's why it would be handy to have them in an multidimensional array
Thanks in advance.
It becomes pretty trivial once you start turning it inside out and "wrap" the inner array into successive outer arrays:
$result = array_reduce(array_reverse($structures), function ($result, $key) {
return [$key => $result];
}, ['more_attributes' => true]);
Obviously a more complex solution would be needed if you needed to set multiple paths on the same result array, but this is the simplest solution for a single path.
Slightly different approach:
$var = array('a','an','asd','asdf');
$var2 = array_reverse($var);
$result = array('more_attributes' => true);
$temp = array();
foreach ($var2 as $val) {
$temp[$val] = $result;
$result = $temp;
$temp = array();
}

Multidimensional Array to String conversion

I have a dynamic multidimensional array and I want to convert it to string.
here is an example:
Array
(
[data] => check
[test1] => Array
(
[data] => Hello
)
[test2] => Array
(
[data] => world
)
[test3] => Array
(
[data] => bar
[tst] => Array
(
[data] => Lorem
[bar] => Array
(
[data] => doller
[foo] => Array
(
[data] => sit
)
)
)
)
[test4] => Array
(
[data] => HELLO
[tst] => Array
(
[data] => ipsum
[bar] => Array
(
[data] => Lorem
)
)
)
)
The example for string is:
check&hello&world&bar...lorem&doller...sit ....
I have tried alot of things. I even checked the solutions given on other SO questions. like:
Convert Multidimensional array to single array & Multidimensional Array to String
But No luck.
You can simply use array_walk_recursive like as
$result = [];
array_walk_recursive($arr, function($v) use (&$result) {
$result[] = $v;
});
echo implode('&', $result);
Demo
First convert it to flat array, by
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($input_array));
$flat = iterator_to_array($it, false);
false prevents array key collision.
Then use implode,
$str = implode('&', $flat);
You can use following recursive function to convert any multidimensional array to string
public function _convertToString($data,&$converted){
foreach($data as $key => $value){
if(is_array($value)){
$this->_convertToString($value,$converted);
}else{
$converted .= '&'. $value;
}
}
}
You can call above function in following way:
$str = array(
"data" => "check",
"test1" => array(
"data" => "Hello",
"test3" => array(
"data" => "satish"
)
),
"test2" => array(
"data" => "world"
)
);
$converted = "";
//call your function and pass your array and reference string
$this->_convertToString($str,$converted);
echo $converted;
Output will be following:
check&Hello&satish&world
you can modify code to meet your requirement.
Let me know if any further help required.
php has some build in functions that can do this. Like var_dump, json_encode and var_export. But if you want to control the output more it can be doen with a recursive function
function arrToStr(array $data)
{
$str = "";
foreach ($data as $val) {
if (is_array($val)) {
$str .= arrToStr($val);
} else {
$str .= $val;
}
}
return $str;
}
You can format extra line breaks and spaces at will with this.
I would use recursion for this type of array :
echo visit($your_array);
function visit($val){
if( !is_array($val) ){
return $val;
}
$out="";
foreach($val as $v){
$out.= "&".visit($v);
}
return $out;
}

Using mysql_real_escape_string in a multidimensional array in php

I am working on a big script which will generate some string or array or multidimensional array i want use mysql_real_escape_string for all array / string
for that this i tried the below code
function check($data) {
if(!is_array($data)) {
return mysql_real_escape_string($data);
} else if (is_array($data)) {
$newData = array();
foreach($data as $dataKey => $dataValue){
if(!is_array($dataValue)){
$key = mysql_real_escape_string($dataKey);
$value = mysql_real_escape_string($dataValue);
$newData[$key] = $value;
}
}
return $newData;
}
}
if i use like this check('saveme'); this returns value
if i pass a array it returns corrent value [ check(array('a','b','c',1,2,3)) ]
if i pass multidimensional array i get [check(array(array('a',array('a','b','c',1,2,3),'c',1,2,3),'b',array('a','b','c',1,2,3),1,2,3))]
A kind note i want to use mysql_real_escape_string for array key too.
You can use array_walk_recursive function, to go throw all leaves of the array, and escape values:
array_walk_recursive($array, function(&$leaf) {
if (is_string($leaf))
$leaf = mysql_real_escape_string($leaf);
});
Also, it is good to follow data consistency rules, and do not use !is_array(), but is_string(), because mysql_real_escape_string takes string params, not !string.
Unfortunately, array_walk_recursive is designed so, that it can't edit keys. If you need edit keys, you may want to write your own recursive function. I don't want to copy answer, you can find it here
You can use this function :
(MyStringEscapeFunc() is your custom escape function)
function escape_recursive($arr){
if(is_array($arr)){
$temp_arr = array();
foreach ($arr as $key=>$value){
$temp_arr[MyStringEscapeFunc($key)] = escape_recursive($value);
}
return $temp_arr;
}else{
return MyStringEscapeFunc($arr);
}
}
Example Result :
//Before :
Array (
[0] => Array (
[0] => foo'bar
[1] => bar'baz
)
[1] => foob'ar
[2] => Array ( [foo'baz] => baz'foo )
)
//After :
Array (
[0] => Array (
[0] => foo\'bar
[1] => bar\'baz
)
[1] => foob\'ar
[2] => Array ( [foo\'baz] => baz\'foo )
)

Flatten array joining keys with values

I have this multidimensional array:
$array = array(
'user1' => array('Miguel'),
'user2' => array('Miguel', 'Borges', 'João'),
'user3' => array(
'Sara',
'Tiago' => array('Male')
)
);
I want it flatten, transformed into:
$new_array = array(
'user1.Miguel',
'user2.Miguel',
'user2.Borges',
'user2.João',
'user3.Sara',
'user3.Tiago.Male',
);
Important:
The keys are very important to me. I want them concatenated,
separated by periods.
It should work with any level of nesting.
Thank you!
Though not explicitly stated in your question, it seems that you need to concatenate the string keys and ignore the integer keys (which may be easily achieved with is_string($key)). And since you need your code to “work with any level of nesting,” a recursive function would serve your purpose best:
function array_flatten_key($arr){
$_arr = array();
foreach($arr as $key => $val){
if(is_array($val)){
foreach(array_flatten_key($val) as $_val){
$_arr[] = is_string($key) ? $key.".".$_val : $_val;
}
}
else{
$_arr[] = is_string($key) ? $key.".".$val : $val;
}
}
return $_arr;
}
$new_array = array_flatten_key($array);
print_r($new_array);
The output will be:
Array
(
[0] => user1.Miguel
[1] => user2.Miguel
[2] => user2.Borges
[3] => user2.João
[4] => user3.Sara
[5] => user3.Tiago.Male
)

weird php array

my php array looks like this:
Array (
[0] => dummy
[1] => stdClass Object (
[aid] => 1
[atitle] => Ameya R. Kadam )
[2] => stdClass Object (
[aid] => 2
[atitle] => Amritpal Singh )
[3] => stdClass Object (
[aid] => 3
[atitle] => Anwar Syed )
[4] => stdClass Object (
[aid] => 4
[atitle] => Aratrika )
) )
now i want to echo the values inside [atitle].
to be specific i want to implode values of atitle into another variable.
how can i make it happen?
With PHP 5.3:
$result = array_map(function($element) { return $element->atitle; }, $array);
if you don't have 5.3 you have to make the anonymous function a regular one and provide the name as string.
Above I missed the part about the empty element, using this approach this could be solved using array_filter:
$array = array_filter($array, function($element) { return is_object($element); });
$result = array_map(function($element) { return $element->atitle; }, $array);
If you are crazy you could write this in one line ...
Your array is declared a bit like this :
(Well, you're probably, in your real case, getting your data from a database or something like that -- but this should be ok, here, to test)
$arr = array(
'dummy',
(object)array('aid' => 1, 'atitle' => 'Ameya R. Kadam'),
(object)array('aid' => 2, 'atitle' => 'Amritpal Singh'),
(object)array('aid' => 3, 'atitle' => 'Anwar Syed'),
(object)array('aid' => 4, 'atitle' => 'Aratrika'),
);
Which means you can extract all the titles to an array, looping over your initial array (excluding the first element, and using the atitle property of each object) :
$titles = array();
$num = count($arr);
for ($i=1 ; $i<$num ; $i++) {
$titles[] = $arr[$i]->atitle;
}
var_dump($titles);
This will get you an array like this one :
array
0 => string 'Ameya R. Kadam' (length=14)
1 => string 'Amritpal Singh' (length=14)
2 => string 'Anwar Syed' (length=10)
3 => string 'Aratrika' (length=8)
And you can now implode all this to a string :
echo implode(', ', $titles);
And you'll get :
Ameya R. Kadam, Amritpal Singh, Anwar Syed, Aratrika
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
echo $item->atitle;
}
}
to get them into an Array you'd just need to do:
$resultArray = array();
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
$resultArray[] = $item->atitle;
}
}
Then resultArray is an array of all the atitles
Then you can output as you'd wish
$output = implode(', ', $resultArray);
What you have there is an object.
You can access [atitle] via
$array[1]->atitle;
If you want to check for the existence of title before output, you could use:
// generates the title string from all found titles
$str = '';
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$str .= $v->title;
}
}
echo $str;
If you wanted these in an array it's just a quick switch of storage methods:
// generates the title string from all found titles
$arr = array();
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$arr[] = $v->title;
}
}
echo implode(', ', $arr);
stdClass requires you to use the pointer notation -> for referencing whereas arrays require you to reference them by index, i.e. [4]. You can reference these like:
$array[0]
$array[1]->aid
$array[1]->atitle
$array[2]->aid
$array[2]->atitle
// etc, etc.
$yourArray = array(); //array from above
$atitleArray = array();
foreach($yourArray as $obj){
if(is_object($obj)){
$atitleArray[] = $obj->aTitle;
}
}
seeing as how not every element of your array is an object, you'll need to check for that.

Categories