Expand (json) object in php - php

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

Related

Output JSON array append additional element PHP

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]['Pub‌​lisherCount'];
$temp_array[] = $row;
}
$publisher_apps = $temp_array;
$result = array("apps"=>$publisher_apps);
output_json($result);

PHP: show only last data from same data on loop

i have data from php loop foreach like this
foreach ($query->result() as $row) {
echo $row->name;
}
how to make the result show only the end data without remove others if data has same (if data have same value, hide all except the last one) like this:
*sorry bad english, this is the first time i ask here. thank you
Online Check, This is just a demo example.
See below the real example:
At first you need to use array_search for get the position of the same data, if exist then just remove it using $arr[$pos] = '';, and each and every time you need to import data into the new array called $arr and after completing fetching data you need to use a foreach loop to print them.
$arr = array();
foreach($query->result() as $row){
$pos = array_search($row->name, $arr);
if($pos !== false)
$arr[$pos] = '';
$arr[] = $row->name;
}
foreach($arr as $val){
echo $val.'<br/>';
}
Check this and let me know.
The data_seek method might help. This assumes your array is reasonable ordered to begin with.
$rowCount = 0;
$res = $query->result();
foreach($res as $row) {
if ($rowCount < $res->num_rows - 1) {
// set internal pointer to next row
$res->data_seek($rowCount + 1);
// if the row names match, print an empty string
// otherwise print the current name
$nextRow = $res->fetch_row();
if ($row->name == $nextRow->name) {
echo "";
// reset the internal pointer
$res->data_seek($rowCount);
} else {
echo $row->name;
}
} else {
echo $row->name;
}
// update the row count
$rowCount += 1;
}

PHP fill up an associative array

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

Returning values from an array

Is there any reason why this code would avoid the first value in an array?
$rappels = array();
$i = 0;
while($row = $result->fetch_assoc()) {
foreach($row as $key=>$val) {
$rappels[$i][$key] = $val;
}
$i++;
}
return $rappels;
When I return the rappels, it always seems to avoid returning the very first item, which should be [0] in the array.
You have a number of redundancies in your code. You don't need $i nor do you need the foreach loop.
$rappels = array();
while($row = $result->fetch_assoc()) {
$rappels[] = $row;
}
return $rappels;
Your code as you posted it shouldn't remove any rows. You may need to look at the code you haven't posted to see if there's something there that's skipping the first row.

PHP/MySQL: Why is my query only returning the first row?

Why is my method only returning the first row of my table? I can't understand why and it's driving me nuts. I'm sure it's something very simple.
public function getTitlesForRegistrationForm() {
$result = $this->_db->query("SELECT UserTitleID, UserTitleName FROM UserTitles");
$i=0;
$array[0] = "No result";
foreach($result->fetch(PDO::FETCH_ASSOC) as $row){
$array[$i] = $row;
$i++;
}
return $array;
}
Thanks.
It may be because your $result->fetch() call doesn't return an iterable value, but either a result row or FALSE. PHP's foreach only works on iterable values. Updating your code to something like this should do the trick:
public function getTitlesForRegistrationForm() {
$result = $this->_db->query("SELECT UserTitleID, UserTitleName FROM UserTitles");
$i=0;
$array[0] = "No result";
while (($row = $result->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
$array[$i] = $row;
$i++;
}
return $array;
}
You need to fetch() inside a while loop. It will return only one row each time it is called.
I've also taken the liberty of refactoring away your $i counter. Instead the No result is appended onto the array in the first position (for whatever purpose you planned to use it), and subsequent rows are appended on with [].
public function getTitlesForRegistrationForm() {
$array = array();
$result = $this->_db->query("SELECT UserTitleID, UserTitleName FROM UserTitles");
// Why are you putting No Result onto the array?
// I've left it in, but it doesn't make sense to me.
$array[] = "No result";
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$array[] = $row;
}
return $array;
}
It's because you are using fetch(). You need fetchall().
http://www.php.net/manual/en/pdostatement.fetchall.php
[edit]Wow. I need to learn to type faster.
Try:
while($row = $result->fetch(PDO::FETCH_ASSOC)){
foo();
}
Try while instead of foreach. Foreach only iterates over a single row that is returned.
code:
while($row = fetch(PDO::FETCH_ASSOC)) {
$array[$i] = $row;
$i++;
}
Just replace the fetch method with fetchAll

Categories