How to convert a multidimensional associative array to JSON? - php

As you can see in the JSON file, this looks not so necessary.
I get values from input-s and add it to the array and send it via AJAX. A simple array I know how to convert, but a multidimensional one is not. Can eat what that function? I tried to create an array with "keys", but there is a lot of trouble, I never reached the end , and I'm sure it's not right. Tell me what you can do.
i want this
{
"user1" : {
first_name":"Michael",
"last_name":"Podlevskykh",
"phones" : {
"phone_1":"5345",
"phone_2":"345345",
"phone_3":"123"
}
}
}
//this is what i see
JSON
[
{"first_name":"Michael"},
{"last_name":"Podlevskykh"},
[{"phone_1":"5345"},
{"phone_2":"345345"},
{"phone_3":"0991215078"}
]
]
PHP
//[["5345", "345345", "123"], "Michael", "Podlevskykh"]
$userInfo = (json_decode($_POST["phones"], true));
$namePhones = ["phone_1", "phone_2", "phone_3"];
$nameUser = ["first_name", "last_name"];
$jsonPhones = $userInfo;
$nameLName = $userInfo;
$jsonPhones = array_splice($jsonPhones, 0, 1);
$nameLName = array_splice($nameLName, -2);
foreach ($jsonPhones[0] as $key => $value) {
$phones[] = array($namePhones[$key] => $jsonPhones[0][$key]);
}
foreach ($nameLName as $key => $value) {
$usersName[] = array($nameUser[$key] => $nameLName[$key]);
}
array_push($usersName, $phones);
echo "<pre>";
echo json_encode($usersName);
//[
// {"first_name":"Michael"},{"last_name":"Podlevskykh"},
// [{"phone_1":"5345"},{"phone_2":"345345"},{"phone_3":"123"}]
//]

I don't get all the complications, I would do something like this if I'm sure the $input format is the same:
<?php
$input = '[["5345", "345345", "123"], "Michael", "Podlevskykh"]';
$input = json_decode($input, true);
$output = [
'user1' => [
'first_name' => $input[1],
'last_name' => $input[2],
'phones' => [
'phone_1' => $input[0][0],
'phone_2' => $input[0][1],
'phone_3' => $input[0][2]
]
]
];
echo '<pre>';
echo json_encode($output);

If you want an object as output, you need to create an object:
$userInfo = (json_decode($_POST["phones"], true));
$namePhones = ["phone_1", "phone_2", "phone_3"];
$nameUser = ["first_name", "last_name"];
$jsonPhones = $userInfo;
$nameLName = $userInfo;
$jsonPhones = array_splice($jsonPhones, 0, 1);
$nameLName = array_splice($nameLName, -2);
$user = new stdClass();
foreach ($nameLName as $key => $value) {
$user->{$nameUser[$key]} = $nameLName[$key];
}
$phones = new stdClass();
foreach ($jsonPhones[0] as $key => $value) {
$phones->{$namePhones[$key]} = $jsonPhones[0][$key];
}
$user->phones = $phones;
$users = new stdClass();
$users->user1 = $user;
echo json_encode($users);
Output:
{"user1": {
"first_name":"Michael",
"last_name":"Podlevskykh",
"phones":{
"phone_1":"5345",
"phone_2":"345345",
"phone_3":"123"
}
}
}

Related

make foreach into json array

I'm a little confused, and I need help.
I have a foreach loop in my code below. I need to put the foreach loop into the $data = array('image' => $final_image);
How can i put foreach loop in array ? Anyone can help me please.
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
}
echo $final_image;
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_image,
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
// Create an array to store final images
$final_images = [];
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
// Save the image if its new data.
$final_images[]= $final_image;
}
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_images, // We pass the final images array
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}
Made things a bit more verbose.
First define the array.
Then in the if statement add element to the array.
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
$final_images = array(); // Define object as array
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
$final_images[] = array('image' => $final_image); // Will create new array item
}
echo $final_image;
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_image,
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}

Looping through a JSON in PHP

I'm trying to loop through a JSON that I post to my PHP backend. The JSON looks like this:
[
{
"number":"5613106"
},
{
"number":"56131064"
},
{
"number":"56131063"
}
]
I post it from Postman like so:
I want to be able to print each number that I've posted individually using
echo $number;
Right now when I use the following it just prints the last number:
$number = $json['number'];
echo $number;
My function:
public function check_users_post()
{
$json = $this->request->body;
print_r($json);
$this->response($json, REST_Controller::HTTP_OK);
}
The output:
Array
(
[0] => Array
(
[number] => 5613106
)
[1] => Array
(
[number] => 56131064
)
[2] => Array
(
[number] => 56131063
)
)
Hope this generic iterator will help you.
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Use
json_decode()
PHP built in function for decoding json back to PHP variable or array and then loop through each index and print number.
Got it done like this:
public function check_users_post()
{
$json = $this->request->body;
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($json),
RecursiveIteratorIterator::SELF_FIRST);
$phone_numbers = "";
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
} else {
$phone_numbers = "$phone_numbers" . ", " . "$val";
}
}
$phone_numbers = substr($phone_numbers, 2);
$phone_numbers = "(" . $phone_numbers . ")";
$query = $this->db->query("SELECT * FROM users WHERE user_number in $phone_numbers;");
$result = $query->result();
$this->response($result, REST_Controller::HTTP_OK);
if (mysql_num_rows($result)==0) {
$data = [ 'message' => 'No users returned'];
$this->response($data, REST_Controller::HTTP_BAD_REQUEST);
} else {
$this->response($result, REST_Controller::HTTP_OK);
}
}
Description
First stringify your JSON, than use JSON_DECODE() function which gives you the array afterwards iterate on this array using foreach loop which will give you the each key which you want to echo.
Code
$str = '[
{
"number":"5613106"
},
{
"number":"56131064"
},
{
"number":"56131063"
}
]';
$array = json_decode($str, true);
echo "<pre>";
foreach ($array as $key => $key_value) { // then loop through it
echo "<br>";
echo $array[$key]['number'];
echo "<br>";
}
Output
5613106
56131064
56131063

Creating a dynamic hierarchical array in PHP

I have this general data structure:
$levels = array('country', 'state', 'city', 'location');
I have data that looks like this:
$locations = array(
1 => array('country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'count'=>123),
2 => array('country'=>'Germany', ... )
);
I want to create hierarchical arrays such as
$hierarchy = array(
'USA' => array(
'New York' => array(
'NYC' => array(
'Central Park' => 123,
),
),
),
'Germany' => array(...),
);
Generally I would just create it like this:
$final = array();
foreach ($locations as $L) {
$final[$L['country']][$L['state']][$L['city']][$L['location']] = $L['count'];
}
However, it turns out that the initial array $levels is dynamic and can change in values and length So I cannot hard-code the levels into that last line, and I do not know how many elements there are. So the $levels array might look like this:
$levels = array('country', 'state');
Or
$levels = array('country', 'state', 'location');
The values will always exist in the data to be processed, but there might be more elements in the processed data than in the levels array. I want the final array to only contain the values that are in the $levels array, no matter what additional values are in the original data.
How can I use the array $levels as a guidance to dynamically create the $final array?
I thought I could just build the string $final[$L['country']][$L['state']][$L['city']][$L['location']] with implode() and then run eval() on it, but is there are a better way?
Here's my implementation. You can try it out here:
$locations = array(
1 => array('country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'count'=>123),
2 => array('country'=>'Germany', 'state'=>'Blah', 'city'=>'NY', 'location'=>'Testing', 'count'=>54),
);
$hierarchy = array();
$levels = array_reverse(
array('country', 'state', 'city', 'location')
);
$lastLevel = 'count';
foreach ( $locations as $L )
{
$array = $L[$lastLevel];
foreach ( $levels as $level )
{
$array = array($L[$level] => $array);
}
$hierarchy = array_merge_recursive($hierarchy, $array);
}
print_r($hierarchy);
Cool question. A simple approach:
$output = []; //will hold what you want
foreach($locations as $loc){
$str_to_eval='$output';
for($i=0;$i<count($levels);$i++) $str_to_eval .= "[\$loc[\$levels[$i]]]";
$str_to_eval .= "=\$loc['count'];";
eval($str_to_eval); //will build the array for this location
}
Live demo
If your dataset always in fixed structure, you might just loop it
$data[] = [country=>usa, state=>ny, city=>...]
to
foreach ($data as $row) {
$result[][$row[country]][$row[state]][$row[city]] = ...
}
In case your data is dynamic and the levels of nested array is also dynamic, then the following is an idea:
/* convert from [a, b, c, d, ...] to [a][b][...] = ... */
function nested_array($rows, $level = 1) {
$data = array();
$keys = array_slice(array_keys($rows[0]), 0, $level);
foreach ($rows as $r) {
$ref = &$data[$r[$keys[0]]];
foreach ($keys as $j => $k) {
if ($j) {
$ref = &$ref[$r[$k]];
}
unset($r[$k]);
}
$ref = count($r) > 1 ? $r : reset($r);
}
return $data;
}
try this:
<?php
$locations = [
['country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'street'=>'7th Ave', 'count'=>123],
['country'=>'USA', 'state'=>'Maryland', 'city'=>'Baltimore', 'location'=>'Harbor', 'count'=>24],
['country'=>'USA', 'state'=>'Michigan', 'city'=>'Lansing', 'location'=>'Midtown', 'building'=>'H2B', 'count'=>7],
['country'=>'France', 'state'=>'Sud', 'city'=>'Marseille', 'location'=>'Centre Ville', 'count'=>12],
];
$nk = array();
foreach($locations as $l) {
$jsonstr = json_encode($l);
preg_match_all('/"[a-z]+?":/',$jsonstr,$e);
$narr = array();
foreach($e[0] as $k => $v) {
if($k == 0 ) {
$narr[] = '';
} else {
$narr[] = ":{";
}
}
$narr[count($e[0]) -1] = ":" ;
$narr[] = "";
$e[0][] = ",";
$jsonstr = str_replace($e[0],$narr,$jsonstr).str_repeat("}",count($narr)-3);
$nk [] = $ko =json_decode($jsonstr,TRUE);
}
print_r($nk);
Database have three field:
here Name conatin contry state and city name
id,name,parentid
Pass the contry result to array to below function:
$data['contry']=$this->db->get('contry')->result_array();
$return['result']=$this->ordered_menu( $data['contry'],0);
echo "<pre>";
print_r ($return['result']);
echo "</pre>";
Create Function as below:
function ordered_menu($array,$parent_id = 0)
{
$temp_array = array();
foreach($array as $element)
{
if($element['parent_id']==$parent_id)
{
$element['subs'] = $this->ordered_menu($array,$element['id']);
$temp_array[] = $element;
}
}
return $temp_array;
}

Need help php to json array

I am having a string below
$string = ot>4>om>6>we>34>ff>45
I would like the JSON output be like
[{"name":"website","data":["ot","om","we","ff"]}]
and
[{"name":"websitedata","data":["4","6","34","45"]}]
what I've tried
$query = mysql_query("SELECT month, wordpress, codeigniter, highcharts FROM project_requests");
$category = array();
$category['name'] = 'website';
$series1 = array();
$series1['name'] = 'websitedata';
while($r = mysql_fetch_array($query)) {
$category['data'][] = $r['month'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
print json_encode($result, JSON_NUMERIC_CHECK);
but the above code is applicable only if the data are present in rows from a mysql table, what i want is achieve the same result with the data from the above string. that is
$string = ot>4>om>6>we>34>ff>45
NEW UPDATE:
I would like to modify the same string
$string = ot>4>om>6>we>34>ff>45
into
json output:
[
{
"type" : "pie",
"name" : "website",
"data" : [
[
"ot",
4
],
[
"om",
6
],
[
"we",
34
]
]
}
]
I have updated the answer please check the json part, I would like the php code.
regards
You can explode() on the >s, and then loop through the elements:
$string = "ot>4>om>6>we>34>ff>45";
$array1 = [
'name'=>'website',
'data'=>[]
]
$array2 = [
'name'=>'websitedata',
'data'=>[]
]
foreach(explode('>', $string) as $index => $value){
if($index & 1) //index is odd
$array2['data'][] = $value;
else //index is even
$array1['data'][] = $value;
}
echo json_encode($array1); //prints {"name":"website","data":["ot","om","we","ff"]}
echo json_encode($array2); //prints {"name":"websitedata","data":["4","6","34","45"]}
A solution using preg_match_all():
$string = "ot>4>om>6>we>34>ff>45";
preg_match_all('/(\w+)>(\d+)/', $string, $matches);
$array1 = [
'name'=>'website',
'data'=> $matches[1]
];
$array2 = [
'name'=>'websitedata',
'data'=> $matches[2]
];
echo json_encode($array1); //prints {"name":"website","data":["ot","om","we","ff"]}
echo json_encode($array2); //prints {"name":"websitedata","data":["4","6","34","45"]}
Update:
To get the second type of array you wanted, use this:
//since json_encode() wraps property names in double quotes (which prevents the chart script from working), you'll have to build the json object manually
$string = "ot>4>om>6>we>34>ff>45";
preg_match_all('/(\w+)>(\d+)/', $string, $matches);
$data = [];
foreach($matches[1] as $index => $value){
if(isset($matches[2][$index]))
$data[] = '["' . $value . '",' . $matches[2][$index] . ']';
}
$type = 'pie';
$name = 'website';
echo $jsonString = '[{type:"' . $type . '",name:"' . $name . '",data:[' . implode(',', $data) . ']}]'; // prints [{type:"pie",name:"website",data:[["ot",4],["om",6],["we",34],["ff",45]]}]
Update #2:
This code uses explode(), and although it's probably not the most efficient way of doing it, it works.
//since json_encode() wraps property names in double quotes (which prevents the chart script from working), you'll have to build the json object manually
$string = "ot>4>om>6>we>34>ff>45";
$keys = [];
$values = [];
foreach(explode('>', $string) as $key => $value){
if(!($key & 1)) //returns true if the key is even, false if odd
$keys[] = $value;
else
$values[] = $value;
}
$data = [];
foreach($keys as $index => $value){
if(isset($values[$index]))
$data[] = '["' . $value . '",' . $values[$index] . ']';
}
$type = 'pie';
$name = 'website';
echo $jsonString = '[{type:"' . $type . '",name:"' . $name . '",data:[' . implode(',', $data) . ']}]'; // prints [{type:"pie",name:"website",data:[["ot",4],["om",6],["we",34],["ff",45]]}]
This should work, though there are probably better ways to do it.
$string = "ot>4>om>6>we>34>ff>45";
$website = ["name" => "website", "data" => []];
$websiteData = ["name" => "websitedata", "data" => []];
foreach(explode(">", $string) as $i => $s) {
if($i % 2 === 0) {
$website["data"][] = $s;
} else {
$websiteData["data"][] = $s;
}
}
echo json_encode($website);
echo json_encode($websiteData);
A regex alternative:
preg_match_all("/([a-z]+)>(\d+)/", $string, $matches);
$website = ["name" => "website", "data" => $matches[1]];
$websiteData = ["name" => "websitedata", "data" => $matches[2]];
Try this code:
$string = 'ot>4>om>6>we>34>ff>45';
$string_split = explode('>', $string);
$data = array("name" => "website");
$data2 = $data;
foreach ($string_split as $key => $value)
{
if (((int)$key % 2) === 0)
{
$data["data"][] = $value;
}
else
{
$data2["data"][] = $value;
}
}
$json1 = json_encode($data, JSON_NUMERIC_CHECK);
$json2 = json_encode($data2, JSON_NUMERIC_CHECK);
echo $json1;
echo $json2;
Output:
{"name":"website","data":["ot","om","we","ff"]}
{"name":"website","data":[4,6,34,45]}
Regards.
Try this snippet:
$strings = explode('>', 'ot>4>om>6>we>34>ff>45');
// print_r($string);
$x = 0;
$string['name'] = 'website';
$numbers['name'] = 'websitedata';
foreach ($strings as $s)
{
if ($x == 0) {
$string['data'][] = $s;
$x = 1;
} else {
$numbers['data'][] = $s;
$x = 0;
}
}
print_r(json_encode($string));
echo "<br/>";
print_r(json_encode($numbers));
As usual - it is long winded but shows all the steps to get to the required output.
<?php //https://stackoverflow.com/questions/27822896/need-help-php-to-json-array
// only concerned about ease of understnding not code size or efficiency.
// will speed it up later...
$inString = "ot>4>om>6>we>34>ff>45";
$outLitRequired = '[{"name":"website","data":["ot","om","we","ff"]}]';
$outValueRequired = '[{"name":"websitedata","data":["4","6","34","45"]}]';
// first: get a key / value array...
$itemList = explode('>', $inString);
/* debug */ var_dump(__FILE__.__LINE__, $itemList);
// outputs ------------------------------------
$outLit = array();
$outValue = array();
// ok we need to process them in pairs - i like iterators...
reset($itemList); // redundant but is explicit
// build both output 'data' lists
while (current($itemList)) {
$outLit[] = current($itemList);
next($itemList); // advance the iterator.
$outValue[] = current($itemList);
next($itemList);
}
/* debug */ var_dump(__FILE__.__LINE__, $itemList, $outLit, $outValue);
// make the arrays look like the output we want...
// we need to enclose them as arrays to get the exact formatting required
// i do that in the 'json_encode' statements.
$outLit = array('name' => 'website', 'data' => $outLit);
$outValue = array('name' => 'websitedata', 'data' => $outValue);
// convert to JSON.
$outLitJson = json_encode(array($outLit));
$outValueJson = json_encode(array($outValue));
// show required and calculated values...
/* debug */ var_dump(__FILE__.__LINE__, 'OutLit', $outLitRequired, $outLitJson);
/* debug */ var_dump(__FILE__.__LINE__, 'OutValue', $outValueRequired, $outValueJson);

No Data & No Error when using function inside IF Statement

I am having trouble getting my php script to work when using a function in if statements.
The code currently runs, but doesn't give me any information, nor any errors, if I remove the IF'S it works fine, but the project I am working on, this is essential.
Here is my code - I have took out the SQL to save space..
if ($VAR === 'PK%') {
CDB::UseDB('blah', 'blah', 'blah', 'blah');
$sql = "blah blah
";
$lrs = CDB::ExecuteQuery($sql);
if ($lrs) {
$jsonData = convert($lrs);
function convert($lrs)
{
// RE-GET VARIABLE AS IT CAN'T GET IT FROM OUTSIDE OF FUNCTION
$VAR = $_GET['VARIABLE'];
$intermediate = array();
while ($vals = CDB::GetAssoc($lrs)) {
$key = $vals['VAR'];
$y = $vals['MEASURE_1'];
if (!isset($intermediate[$key])) $intermediate[$key] = array();
$intermediate[$key][] = array('x' => count($intermediate[$key]), 'y' => $y);
}
$output = array();
foreach ($intermediate as $key => $values) {
$output[] = array(
"key" => $key,
'values' => $values
);
}
return json_encode($output, JSON_NUMERIC_CHECK);
}
}
}
Can anyone shed some light on what I am doing wrong?
You are defining your function in a conditional way. In that case its definition must be processed prior to being called.
I would recommend declaring your function separately and then use it, like:
function convert($lrs) {
// RE-GET VARIABLE AS IT CAN'T GET IT FROM OUTSIDE OF FUNCTION
$VAR = $_GET['VARIABLE'];
$intermediate = array();
while ($vals = CDB::GetAssoc($lrs)) {
$key = $vals['VAR'];
$y = $vals['MEASURE_1'];
if (!isset($intermediate[$key])) $intermediate[$key] = array();
$intermediate[$key][] = array('x' => count($intermediate[$key]), 'y' => $y);
}
$output = array();
foreach ($intermediate as $key => $values) {
$output[] = array(
"key" => $key,
'values' => $values
);
}
return json_encode($output, JSON_NUMERIC_CHECK);
}
if ($VAR === 'PK%') {
CDB::UseDB('blah', 'blah', 'blah', 'blah');
$sql = "blah blah";
$lrs = CDB::ExecuteQuery($sql);
if ($lrs) {
$jsonData = convert($lrs);
}
}

Categories