I'm pretty sure I'm quite close so hopefully quick answer.
I'm able to generate this JSON:
apps: [
{
0: {
PublisherCount: "7"
},
Id: "87",
AppName: "Productivity, Focus, Habits & Life Success by Audiojoy",
AppBundle: "productivitymind"
}
]
But I'm trying to get to:
apps: [
{
Id: "87",
AppName: "Productivity, Focus, Habits & Life Success by Audiojoy",
AppBundle: "productivitymind",
PublisherCount: "7"
}
]
Here is my output loop (I think the issue is in the 5th row where I array_push the new value for PublisherCount. It creates an additional node instead of adding it to the end.
$temp_array = array();
$i = 0;
while ($row = mysqli_fetch_assoc($publisher_apps)) {
$temp_array[] = $row;
$temp_array[$i][] = fetch_all(get_publisher_count_by_app_id($row['Id']))[0];
$i++;
}
$publisher_apps = $temp_array;
$result = array("apps"=>$publisher_apps);
output_json($result);
Thanks.
You have rows like this:
['Id' => "87",
'AppName' => "Productivity, Focus, Habits & Life Success by Audiojoy",
'AppBundle' => "productivitymind"]
and fetch_all(get_publisher_count_by_app_id($row['Id']))[0] returns an array like this:
['PublisherCount' => 7]
so when you append it with $temp_array[$i][], the entire array gets assigned to the 0 key of $temp_array[$i].
There are various different ways you could get just the PublisherCount value. One way is to use array_merge to combine the result of get_publisher_count_by_app_id with $row, and then add the modified $row to your main array.
while ($row = mysqli_fetch_assoc($publisher_apps)) {
$count = fetch_all(get_publisher_count_by_app_id($row['Id']))[0];
$temp_array[] = array_merge($row, $count);
}
If you do it this way, $i should become unneccessary.
Change it to this:
$temp_array = array();
while ($row = mysqli_fetch_assoc($publisher_apps)) {
$row['PublisherCount'] = fetch_all(get_publisher_count_by_app_id($row['Id']))[0]['PublisherCount'];
$temp_array[] = $row;
}
$publisher_apps = $temp_array;
$result = array("apps"=>$publisher_apps);
output_json($result);
Related
I want this sql-query result (from a log file, i hope it's accurate)
[
{"id":"1","text":"123"}
,{"id":"2","text":"456"}
] []
to become this
{
1: {"id":"1","text":"123"}
,2: {"id":"2","text":"456"}
}
I tried array_push and array_combine but am new to PHP and was unsuccessful so far.
Short: I want to add keys (starting with 1) to an array of objects.
One attempt
$i = 1;
while ($row = fetchRow($result)) {
array_push($arr_result, $row);
array_push($i, $arr_result);
$i++;
}
But $arr_result looks like the first code sample.
You dont need $i using $arr_result[] will create a new occurance in your array.
while ($row = fetchRow($result)) {
// this forces the array to start at 1 instead of 0 if thats what you really want
if (count($arr_result) == 0){
$arr_result[1] = $row;
} else {
$arr_result[] = $row;
}
}
Or if the key is supposed to be the id from the row
while ($row = fetchRow($result)) {
$arr_result[$row['id']] = $row;
}
I am trying to know if the new data can be added to JSON before encoding it?
I am retrieving the data from MySQL database in the following way:
//fetch the data from the database
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$to_encode[] = $row;
}
which gives me this:
[
{
name: "aaa"
},
{
name: "bbb"
}
]
Then I encode it to JSON with:
$array1 = json_encode($to_encode)
I wanted to know if I can add more data into the array before encoding it to make it like this?
[
{
name: "aaa"
age: '5'
},
{
name: "bbb"
age: '5'
}
]
or should I decode the encoded JSON, add the new values and then encode it back?
Simply you can do like this:
//fetch the data from the database
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$to_encode[] = $row;
}
for ($i = 0; $i < count($to_encode); $i++) {
$to_encode[$i]['age'] = '14';
}
$array1 = json_encode($to_encode);
print_r($array1);
Try something like this :
$i=0;
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$to_encode[$i]["name"] = $row;
$to_encode[$i]["age"] = 5;
$i++;
}
$array1 = json_encode($to_encode)
You can push an array to the $row variable, the idea is to build the array before you use json_encode
$to_encode = [];
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$age = array('age'=>5);
array_push($to_encode,$row);
array_push($to_encode,$age);
}
$array = json_encode($to_encode);
My Mysqli Updated Query and it Outputs this
SELECT milestone.id, milestone.name, milestone.date, milestone.location, milestone.story_body, milestone.short_link, milestone.created_at,
GROUP_CONCAT(images.path) as path , images.update_type
FROM milestone
INNER JOIN images ON milestone.id = images.update_id
WHERE milestone.business_id = '1' && milestone.status = '1' && images.update_type = '3'
GROUP BY milestone.id
How Can I form JSON object using above query?
I've tried below method which doesn't give any result
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
I want something like this -
[
{
"id":"4",
"name":"2nd anniversary",
"date":"2015-12-17",
"location":"Mumbai",
"story_body":"Gzjjs jdk djks jdks jdkd jx djdb djd JD djbd djdj d",
"short_link":"izWfs",
"created_at":"2015-12-11 03:49:52",
"path":
[
{"\/SupportData\/ImpalzB2B\/uploads\/90294930451448437444826.jpg"},
{"\/SupportData\/ImpalzB2B\/uploads\/90294930451449758248579.jpg"}
],
"update_type":"3"
},
{
"id":"7",
"name":"#1styearAnniversary",
"date":"2016-01-20",
"location":"Mumbai",
"story_body":"Bsjsj jdkdk djdkdk dkdkf kdkf dkfj fjfj fjfkjdd djkd",
"short_link":"FHXh0",
"created_at":"2016-01-20 23:10:54",
"path":"\/SupportData\/ImpalzB2B\/uploads\/11453356652175.jpg",
"update_type":"3"
}
]
Note: I know Mysql is not being used in PHP 7. I need to replace it with PDO & Mysqli so please neglect that mistake. I am working on same meanwhile I am facing this query.
You can do this now -
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$temp= explode(',', $row['path']); // explode by ,
if(count($temp) > 1) { // More than one element then assign
$row['path']= $temp;
}
$result_array[] = $row;
}
I'm creating a data.php file which returns a json file to a html file where I fill up a grid with the data from the data.php file.
I need this to be an associative array in the following form:
[
{"CompanyName":"Alfreds Futterkiste","ContactName":"Maria Anders","ContactTitle":"Sales Representative"},
{"CompanyName":"Ana Trujillo Emparedados y helados","ContactName":"Ana Trujillo","ContactTitle":"Owner"},
{"CompanyName":"Antonio Moreno Taquera","ContactName":"Antonio Moreno","ContactTitle":"Owner"}
]
Now the problem is, I want this data.php to be sort of generic, which means I don't know the columnnames nor the the amount of columns.
The only way I get this done, is by using a switch statement but this is not ideal (because I can make a number of cases but what if the table has one more column) nor is it very elegant.
I bet this can be done far better, any ideas ?
I tried using array_push() but that doesn't work with associative arrays.
// get columnnames
for ($i = 0; $i < $result->columnCount(); $i++) {
$col = $result->getColumnMeta($i);
$columns[] = $col['name'];
}
// fill up array
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
switch (count($columns);) {
case 1 :
$records[] = array($columns[0] => $row[$columns[0]]);
break;
case 2 :
$records[] = array($columns[0] => $row[$columns[0]], $columns[1] => $row[$columns[1]]);
break;
case 3 :
$records[] = array($columns[0] => $row[$columns[0]], $columns[1] => $row[$columns[1]], $columns[2] => $row[$columns[2]]);
break;
case ... // and so on
}
}
// send data to client
echo json_encode($records);
change the switch code segment with this one
$arr_tmp = array();
for($i = 0; $i < count($columns); $i++)
{
$arr_tmp[$columns[$i]] = $row[$columns[$i]];
}
$records []= $arr_tmp;
You could iterate over the columns:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$values = array();
foreach ($columns as $column) {
values[$column] = $row[$column];
}
records[] = $values;
}
I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}