make foreach into json array - php

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);
}

Related

Yii2 merge arrays

I need merge arrays for json API. I have 3 requests:
$data['winners'] = Winners::find()->limit(8)->all();
$user = User::findIdentity($value->user_id);
$product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();
I need foreach all $data['winners'], get User with id from $data['winners'], and get Product from $data['winners']. After i need merge in 1 json all my data.
I try like this:
$data['winners'] = Winners::find()->limit(8)->all();
foreach ($data['winners'] as $value){
$user = User::findIdentity($value->user_id);
$product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();
$result = ArrayHelper::merge($product, $user);
}
There is an even more elegant solution in PHP:
$winners = Winners::find()->limit(8)->all();
foreach ($winners as $value){
$user = User::findIdentity($value->user_id);
$product = Products::find()->localized($lang)
->where(['coupon' => $value->coupon])->one();
$data[] = [
'image'=> $product->prize_image,
'user' => $user->firstname.' '.$user->lastname,
'title' => $product->win_title,
];
}
return $data;
The PHP array operator [] in $data[] adds an array element at the end of the $data array.
If i understand correctly you question you need an array with all the $data[winners] istances and foreach instance merge the related Produce and User
then you could use
$result[] = array_merge($value, $product, $user);
.
$data['winners'] = Winners::find()->limit(8)->all();
foreach ($data['winners'] as $value){
$user = User::findIdentity($value->user_id);
$product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();
$result[] = array_merge($value, $product, $user);
}
I found solution:
$winners = Winners::find()->limit(8)->all();
$i = 0;
foreach ($winners as $value){
$user = User::findIdentity($value->user_id);
$product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();
$data[$i]['image'] = $product->prize_image;
$data[$i]['user'] = $user->firstname.' '.$user->lastname;
$data[$i]['title'] = $product->win_title;
$i++;
}
return $data;

How to convert JSON string to arrays

With php, I need to convert json arrays into arrays, what should I do, json_encode didn't work for me, thanks in advance for help.
//json sequence
[
{
"name":"Menu",
"sub":
[
{
"name":"Menu 2",
"url":"menu-2.php"
}
]
}
]
this way i should do
array(
'name' => 'Menu',
'sub' => array(
array(
'name' => 'Menu 2',
'url' => 'menu-2.php'
)
)
)
i am creating json array with this function
Do I have to make a change here? I'm not really good in arrays.
<?php
$connect = new PDO("mysql:host=localhost; dbname=propanel_001", "root", "");
$parent_category_id = "";
$query = "SELECT * FROM tb_sayfalar";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$data = get_node_data($parent_category_id, $connect);
}
echo json_encode(array_values($data));
function get_node_data($parent_category_id, $connect)
{
$query = "SELECT * FROM tb_sayfalar WHERE parent_id = '".$parent_category_id."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = array();
foreach($result as $row)
{
$sub_array = array();
if (array_values(get_node_data($row['id'], $connect))) {
$sub_array['name'] = $row['page_name'];
$sub_array['sub'] = array_values(get_node_data($row['id'], $connect));
}else{
$sub_array['name'] = $row['page_name'];
$sub_array['url'] = $row['page_url'].".php";
}
$output[] = $sub_array;
}
return $output;
}
?>
This is what you need, json_decode($json,true);
<?php
$json = '[{"name":"Menu","sub":[{"name":"Menu 2","url":"menu-2.php"}]}]';
$array = json_decode($json,1);
print_r($array[0]);
?>
DEMO: https://3v4l.org/JZQCn
OR use it as a parsable string representation of a variable with var_export()
<?php
$json = '[{"name":"Menu","sub":[{"name":"Menu 2","url":"menu-2.php"}]}]';
$array = var_export(json_decode($json,1)[0]);
print($array);
?>
DEMO: https://3v4l.org/rLA9R
You must use json_decode to convert JSON representing Object to Associative array.
Example Code
$resArr = json_decode($response, true);
For more information look at PHP JSON_DECODE

How to convert a multidimensional associative array to JSON?

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"
}
}
}

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);

Categories