Excluding numbered-index elements of PDO::fetchAll() - php

$allrows = $pdo->fetchAll(); // select * from ....
I want to transform this $allrows into JSON by doing :
echo (json_encode($allrowl,JSON_PRETTY_PRINT));
My problem is that this fetchAll will not only extracting data as associate array but also indexed array for each element, hence repeating elements.
[
{
"org_id": "1",
"0": "1",
"category": "A",
"1": "A",
},
{
"org_id": "2",
"0": "2",
"category": "A",
"1": "A",
}
]
Thank you.

That's becuase the default fetch mode is FETCH_BOTH. CHange your mode to FETCH_ASSOC and you'll only get the non-numeric keys.
Assuming $pdo is a PDOStatement, set it like this prior to the fetch.
$pdo->setFetchMode(PDO::FETCH_ASSOC);
You can also set it in the fetch statement:
$pdo->fetchAll(PDO::FETCH_ASSOC);

Use PDO::FETCH_ASSOC to get only the associated arrays:
$allrows = $pdo->fetchAll(PDO::FETCH_ASSOC);

Related

How to get a specific value from a json array out of a list of arrays

everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).

Unset all data except the data associated with a given value in url

I have a file that sends a request through curl, when I hit the url which is formatted as http://www.example.com/api/something?id=24 I get a series of arrays back in JSON form. It looks like:
24: {
pe: {
id: "24",
name: "Blah",
engine_src: "blah",
each_lender: "1",
soap_request: "0",
lenders: {
0: "3",
1: "1",
2: "6",
3: "12"
}
},
lenders: {
0: {
id: "1",
platform_id: "2",
lender_id: "3",
engine_id: "24",
status: "1",
engine_lender_id: "3",
engine_lender_name: "choice #1"
},
}
There are several other numbers and arrays in the list that look similar. I need to return the array that is associated with the id in the url and only that array.
I have set a new variable which looks like
$selected = (int)$_REQUEST['pe'];
How do I unset all other values except what is in my $selected variable?
Ok, then, assuming your response is in the variable $jsonresponse...
$selected = json_decode($jsonresponse,$assoc=TRUE);
$selected = $selected[$id];
Thank you for your help Charlene. This is how I ended up solving the problem. It is the same concept that Charlene posted just a slightly different format.
$selected = (int)$_REQUEST['pe'];
$save_me = $data[$selected];
unset($data);
$data = $save_me;
print_r($data);

How to fetch PHP database values in Json?

I have to create Matrix tree view in my project. So am plan to use json. My question is how to fetch PHP values in Json ?. I did static matrix tree but i want dynamic. Thank you for advance.
My code is following:
<?php
include('db.php');
$select = mysql_query("select * from table1");
while($row = mysql_fetch_array($select))
{
?>
{
"name": "A", // Here database values come $row['name'];
"children": [
{
"name": "B",
"children": [
{"name": "B-1"}
]
},
{
"name": "C",
"children": [
{"name": "C-1", "size": 1082},
{"name": "C-2", "size": 1681}
]
},
{
"name": "D",
"children": [
{
"name": "D-1",
"children": [
{"name": "D-1 1", "size": 1302},
{"name": "D-1 2", "size": 6703}
]
},
{"name": "D-2", "size": 16540}
]
}
]
}
<?php
}
?>
In this example Im using the mysqli driver. Do not use the mysql driver.
you just need to convert your output data into a json object.
Its possible to extract all the rows at once which is going to give you a marginally less overhead.
$data = mysqli_fetch_all($select); // returns everything in an associative array
$json_data = json_encode($data); // converts that array to json.
if you need specific keys, then manipulate your query to rename columns as necessary eg.
$query = "select name as firstname from ....";
You can just retrieve data from your database and store it in arrays like you normally would. Then call PHP's built in function json_encode() to transform your PHP array into json (assuming your PHP array is well formed (which should be the case if you get it out of a database)).
You could argue that this is slower because you're iterating over the data twice instead of once, but it shouldn't matter, the complexity remains the same.

Proper way to push values to an array PHP?

I have run into a problem that is a little irritating. Here is my PHP code. Ignore where the variables are coming from. This is for shopping-cart functionality but it is applicable in many different areas.
$data_set = json_decode(stripslashes($_POST['varA']), true);
$pid = $pid['product_id'];
$quantity = $pid['quantity'];
$_SESSION['cartid'] = $_SESSION['cartid'] + 1;
$product_data = array("Product_ID" = > $pid, "quantity" = > $quantity, "cartid" = > $_SESSION['cartid']);
My issue is occurring at this place in the code. I first check to see if the Session variable has a value in it, if not then it proceeds to create an associative array.
if (empty($_SESSION['cart_items'])) {
$_SESSION['cart_items'] = array("items" = > $product_data);
} else {
array_push($_SESSION['cart_items']['items'], $product_data);
}
echo json_encode($_SESSION['cart_items']);
The end result after the first item is "added" looks like this:
{
"items": {
"Product_ID": "2",
"quantity": "1",
"cartid": 1
}
}
However, after several the first add, every value gets a key:
{
"items": {
"0": {
"Product_ID": "2",
"quantity": "1",
"cartid": 2
},
"1": {
"Product_ID": "2",
"quantity": "1",
"cartid": 3
},
"Product_ID": "2",
"quantity": "1",
"cartid": 1
}
}
How do I prevent these keys from occuring? Is this possible? If not, how can this be re-written so that the keys are added every time? And is this possible to parse and loop through in JS on the front end?
Sorry I have so many questions. Any help is really appreciated.
In the first iteration, the $_SESSION['cart_items'] is empty, so you run this:
$_SESSION['cart_items'] = array("items" => $product_data);
This creates $_SESSION['cart_items']['items'] but you populate it with just the product by itself; you should define it as an array instead:
$_SESSION['cart_items'] = array("items" => array($product_data));
This creates an array with a single item which you can later extend with array_push.
Having said that, you can replace the whole condition with just:
$_SESSION['cart_items']['items'][] = $product_date;
PHP will automatically create an empty array if it didn't exist yet, followed by adding the product data as the next element.
This is because of this line:
$_SESSION['cart_items'] = array("items" = > $product_data);
You essentially say in that line that 'items' key has product data, instead of key in items. It should be:
$_SESSION['cart_items']['items'] = array($product_data);
Keys -will- always occur, unless you want data to overwrite another. If you do not want keys (0,1 etc) then the only other option is merging data. In which case it would be:
$_SESSION['cart_items']['items']+=$product_data;
..but I don't think that is what you want.
You don't need the items, try the below way.
if (empty($_SESSION['cart_items'])) {
$_SESSION['cart_items'] = array($product_data);
} else {
$_SESSION['cart_items'][] = $product_data;
}

PHP json decode from database

I have this json encode in the database, and i want just echo values name_r in foreach , how is it?
[{
"name_r": "saeed",
"units": ["salam", "11", "11", "khobe", "22", "22", "salam"],
"price_change": ["33", "33", "33", "44", "44", "44"]
}, {
"name_r": "salavat",
"units": ["55", "55", "khobe", "66", "66"],
"price_change": ["77", "77", "77", "88", "88", "88", "99", "99", "99"]
}]
this my php, that have error(Message: Undefined index: name_r - Line Number: 179):
$query = $this->db->query("SELECT * FROM table ORDER BY id desc");
$data = array();
foreach ($query->result() as $row)
{
$data[] = json_decode($row->residence,true);
echo $data["name_r"].'<br>'; //Line Number: 179
}
Assuming that the json_encoded data you provided is stored in one row of the database, the json_decode will give you an array of arrays. To echo all the name_r fields, you would need to:
foreach ($query->result() as $row){
$data = json_decode($row->residence,true);
foreach($data as $datum){
echo $datum['name_r'];
}
}
You used [] in your assignment. This means that the result of the json_decode will be pushed at the end of your array.
Using var_dump($data) should help you understand what your array actually looks like, and solve your problem by yourself.
Assuming the example JSON you showed is data from a single record. The data is an array of objects, so you'll need an inner loops that loops over the array from each returned record.
foreach ($row->residence as &$value) {
$data = json_decode($value,true);
echo $data["name_r"].'<br>';
}
I am not a PHP dev, so I am unsure if my syntax is right. But hopefully you get the idea.

Categories