PHP PDO Convert array to different format - php

I am trying to convert an array obtained by the code below using non-deprecated techniques with php pdo:
$stm = $conn->prepare("SELECT * FROM mysqltable");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
print_r($results);
to the following format required for fusioncharts to be used
[
{
label: "CJ Anderson",
value: "25"
},
{
label: "Imran Tahir",
value: "25"
},
...
...
]
The original array is as follows:
Array (
[0] => Array (
[Id] => 6
[Number] => 1234567890
[Visits] => 1
[Name] => John
)
[1] => Array (
[Id] => 7
[Number] => 1236549871
[Visits] => 9
[Name] => Jerry
)
[2] => Array (
[Id] => 8
[Number] => 2147483647
[Visits] => 3
[Name] => Jane
)
)
Any help would be appreciated, thanks.
EDIT:
As I commented below. I have a full php file that works if you put data in manually. I can't get it to work though when I put the $jsonEncodedData in though. Thoughts?
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- You need to include the following JS file to render the chart.
When you make your own charts, make sure that the path to this JS file is correct.
Else, you will get JavaScript errors. -->
<script src="fusioncharts/js/fusioncharts.js"></script>
</head>
<body>
<?php
try {
# MySQL with PDO_MYSQL
$mysql_host = 'host';
$mysql_database = 'table';
$mysql_username = 'user';
$mysql_password = 'pass';
$conn = new PDO("mysql:host=$mysql_host; dbname=$mysql_database", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
}
catch(PDOException $e) {
echo $e->getMessage();
}
// Form the SQL query that returns the top 10 most populous countries
// Execute the query, or else return the error message.
$stm = $conn->prepare("SELECT Name, Visits FROM mysqltable"); //WHERE Area :SelArea");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
include("fusioncharts.php");
$jsnarray = array();
foreach($results as $k => $v){
$jsnarray[] = array('label' => $results[$k]['Name'], 'value' => $results[$k]['Visits']);
};
$jsonEncodedData=json_encode($jsnarray);
new FusionCharts("type of chart",
"unique chart id",
"width of chart",
"height of chart",
"div id to render the chart",
"type of data",
"actual data");
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": //$jsonEncodedData}'); <---I tried to insert this after "data":but no results unlike if you put raw data**
[
{
"label":"Bakersfield Central",
"value":"880000"
},
{
"label":"Garden Groove harbour",
"value":"730000"
},
{
"label":"Los Angeles Topanga",
"value":"590000"
},
{
"label":"Compton-Rancho Dom",
"value":"520000"
},
{
"label":"Daly City Serramonte",
"value":"330000"
}
]
}');
// Render the chart
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
==============Edit 12/28/15==========
Tried the following code with no results, Question I have is shouldn't we end in "}" as they require that:
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": ' . $jsonEncodedData);
//}';
// Render the chart
print_r($columnChart);
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
I wanted to post the array differences as well between the "manual" method and the "fetch method (above in this edit).
With fetch:
FusionCharts Object ( [constructorOptions:FusionCharts:private] => Array ( >[type] => column2d [id] => ex1 [width] => 600 [height] => 400 [renderAt] => >chart-1 [dataFormat] => json [dataSource] => { "chart": { >"caption":"Harry's SuperMart", "subCaption":"Top 5 stores in last month by >revenue", "numberPrefix":"$", "theme":"ocean" }, "data": >[{"label":"John","value":"125"},{"label":"Jerry","value":"125"},{"label":"Jane","value":"125"}] ) [constructorTemplate:FusionCharts:private] => >[renderTemplate:FusionCharts:private] => )
With Manual Method (that works):
FusionCharts Object ( [constructorOptions:FusionCharts:private] => Array ( >[type] => column2d [id] => ex1 [width] => 600 [height] => 400 [renderAt] => >chart-1 [dataFormat] => json [dataSource] => { "chart": { >"caption":"Harry's SuperMart", "subCaption":"Top 5 stores in last month by >revenue", "numberPrefix":"$", "theme":"ocean" }, "data": [ { >"label":"Bakersfield Central", "value":"880000" }, { "label":"Garden Groove >harbour", "value":"730000" }, { "label":"Los Angeles Topanga", >"value":"590000" }, { "label":"Compton-Rancho Dom", "value":"520000" }, { >"label":"Daly City Serramonte", "value":"330000" } ] } ) >[constructorTemplate:FusionCharts:private] => >[renderTemplate:FusionCharts:private] => )
I see two differences offhand, the manual inserts spaces around "data" and the ending } parameter.

There is an automatic (and much much easier) way of doing this:
$stm = $conn->prepare('SELECT Name AS label, Visits AS value FROM mysqltable;');
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
$jsonEncodedData = json_encode($results);
echo $jsonEncodedData;
Output (locally tested):
[{"label":"Foo","value":"5"},{"label":"Bar","value":"15"}]
That way you can just use it like this:
$columnChart = new FusionCharts('...
...
"data": ' . $jsonEncodedData . '}');
Note the . '}' in the end.
Before Edit:
You could do something like this:
// This part is just for running purposes
$foo = array (
0 => Array (
'Id' => 6,
'Number' => 1234567890,
'Visits' => 1,
'Name' => 'John'
),
1 => array (
'Id' => 7,
'Number' => 1236549871,
'Visits' => 9,
'Name' => 'Jerry'
),
2 => array (
'Id' => 8,
'Number' => 2147483647,
'Visits' => "3", // Example to output quoted
'Name' => 'Jane'
)
);
$bar = array();
foreach($foo as $k => $v){
$bar[] = array('label' => $foo[$k]['Name'], 'value' => $foo[$k]['Visits']);
}
echo json_encode($bar);
Output:
[{"label":"John","value":1},{"label":"Jerry","value":9},{"label":"Jane","value":"3"}]
Compare with yours (from question) in one line:
[{label: "CJ Anderson",value: "25"},{label: "Imran Tahir",value: "25"},...]
Note: I assumed that value is represented by Visit and label by Name.
Read more about json_encode.

As a summary this is the piece that solved the issue including FirstOne's foreach statement:
$stm = $conn->prepare("SELECT Name, Visits FROM mysqltable"); //WHERE Area :SelArea");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
include("fusioncharts.php");
$jsnarray = array();
foreach($results as $k => $v){
$jsnarray[] = array('label' => $results[$k]['Name'], 'value' => $results[$k]['Visits']);
};
$jsonEncodedData=json_encode($jsnarray);
//print_r($jsonEncodedData);
new FusionCharts("type of chart",
"unique chart id",
"width of chart",
"height of chart",
"div id to render the chart",
"type of data",
"actual data");
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": ' . $jsonEncodedData . '}');
// Render the chart
print_r($columnChart);
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
Thanks for everyone's help in solving the issue.

Related

How can I build an multi-dimentional array from a wpdb query return?

I am trying to build a multi-dimensional array from a query return and ran into a problem. Here is a sanitized snippet similar to what I am trying to do. My problem is building the sub array. Any suggestions to get my desired output? I used JSON so it would be more obvious. I can parse an array or JSON.
<?php
// this is my query
global $wpdb;
$locationData = $wpdb->get_results("SELECT
locations.locationID,
locations.location_name,
locations.city,
locations.state,
locations.products,
locations.type,
locations.sku
");
// which returns something like
// [locationID] [location_name] [city] [state] [products] [type] [sku]
// 001 Tulsa Outlet Tulsa OK cakes chocolate 3763
// 001 Tulsa Outlet Tulsa OK cakes lemon 3765
// 001 Tulsa Outlet Tulsa OK sodas coke 4983
// 001 Tulsa Outlet Tulsa OK sodas sprite 4950
// and so on..
// I build an array to be consumed by another function that I created in my plugin:
foreach( $locationData as $key => $location ) {
$output[$row['locationID']] = array(
'locationID' => $row['locationID'],
'location_name' => $row['location_name'],
'products' => array(
// this is where my previous attempts broke down
)
);
$output[$key]['city'] = $location->city;
$output[$key]['state'] = $location->state;
}
// and the $output I need would look like this:
{
"locations" : [
{
"locationID" : "001",
"location_name" : "Tulsa Outlet",
"products" : {
"cakes" : {
"chocolate" : "3763",
"lemon" : "3765"
},
"sodas" : {
"coke" : "4983",
"sprite" : "4950"
}
},
"city" : "Tulsa",
"state" : "ok"
}
]
}
?>
These should help:
$output = [];
foreach ($locationData as $location) {
$locId = $location->locationID;
if (empty($output[$locId])) {
$output[$locId] = [
'locationID' => $location->locationID,
'location_name' => $location->location_name,
'city' => $location->city,
'state' => $location->state,
'products' => [],
];
}
$productType = $location->products;
if (empty($output[$locId]['products'][$productType])) {
$output[$locId]['products'][$productType] = [];
}
$output[$locId]['products'][$productType][$location->type] = $location->sku;
}
Not really sure what you use - $row or $location, so changed everything to $location.
To reindex $output to 0-index array, use array_values.

MongoDB\Driver php How to make inner join with filter in the first collection

I need to make a join between two collections at the same time i need to execute filter for the first collection , exemple :
... // code inside my classe
$this->MDBManager = new MongoDB\Driver\Manager("mongodb:// xxxxx: xxxxx #" . $this->host);
$filter = array ("date", array('$gte' =>str_replace("-","/", "2019-10-5") , '$lte' => str_replace("-","/", 2019-10-15)))
$this->MDBQuery = new MongoDB\Driver\Query($filters, $options);
$this->results = $this->MDBManager->executeQuery("mydb.colllection1", $this->MDBQuery);
so this is my first collection and i need to join the soconde collection id to matche the same value of productEnsembleId attribute in collection 1.
The join request need to be in only one request .
Thnak you so much for your help .
For more details :
exemple collection 1 :
{
"_id": "5db8683c877c34001559f192",
"id": "1BuVJCLGIUIcDXfBQVlpzccAP6r2JRQPGL4wHTEfPildnnWU5gUh8oymfJM2a6wOW117sTbzWJGKLNaRCZ7uMNHA2CnBjT4PeM44B9QaNYMZfg1BiiBa5JYBRLxMLxFTOY88PDFm4U4yDn9iPnljRnfeqpu9ZBl7fGS4tnnlmuz2ntlXb6cFFrFmQIo8EpDOwr5LLyaSrI67mLUya94WMUnDOojXpf4UAjcmMTayM4x9fmla_00001572366396",
"userId": "DEXpMPBstW37YkixF5e6yPeVpkElumYN1nyw0rjjcPy6vf8mdUHXzIg8KMvy0KegxThD5LgKS6WnuhvPwbLqa3aoyhVgIOhk0huqvxmQ0ctBFMVZZyaPkADdGmWUFM10OhTo919uQOb4QgZLZjtDOnTkcmLUfB6uLFdfNmaXLRNaRs6w4GI9ZDwnuVWAgQ3uajWnUTigq1gXbKGcI4G4Es8cBKZsVQhxsKzOqLFGXDONbQEX_00000000000000",
"productEnsembleId": "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"date": "2019/11/01",
"status": "En cours"
}
exmple collextion 2 :
{
"_id": "5da8948e877c34001529a7f2",
"id": "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"name": "ensemble 2",
"image": "fjO9sb3FUmDFhgWn49v1Io5Oa5sdFyL7KZRVzsH0n06n7GtNqIPdFSfDT67BSIvfYSmdTh7IoYyize3SDX169cas4MWMwVWLsF989ZWy76ANsYS4tkLS5OYR1i2TrqXjP40WDCcWvr6OkQapgzuk4hAISx7Mwf6Wp2Z3krzjn72PrTXUDmG7nDrp7VKDrsonCVqkmGs7lAwocdEeghWs7NUVkMdIGMjWDVo8u3wlClzs2e5X_00001571329177",
"produits": null
}
So assuming you want the join results for one document in the first collection, here is a mongo shell query.
db.col1.aggregate([
{ $match: { "_id": "5db8683c877c34001559f192" } },
{ $lookup: {
from: "col2",
localField: "productEnsembleId",
foreignField: "id",
as: "col2_data"
}
}
])
The results look like ...
{
"_id" : "5db8683c877c34001559f192",
"id" : "1BuVJCLGIUIcDXfBQVlpzccAP6r2JRQPGL4wHTEfPildnnWU5gUh8oymfJM2a6wOW117sTbzWJGKLNaRCZ7uMNHA2CnBjT4PeM44B9QaNYMZfg1BiiBa5JYBRLxMLxFTOY88PDFm4U4yDn9iPnljRnfeqpu9ZBl7fGS4tnnlmuz2ntlXb6cFFrFmQIo8EpDOwr5LLyaSrI67mLUya94WMUnDOojXpf4UAjcmMTayM4x9fmla_00001572366396",
"userId" : "DEXpMPBstW37YkixF5e6yPeVpkElumYN1nyw0rjjcPy6vf8mdUHXzIg8KMvy0KegxThD5LgKS6WnuhvPwbLqa3aoyhVgIOhk0huqvxmQ0ctBFMVZZyaPkADdGmWUFM10OhTo919uQOb4QgZLZjtDOnTkcmLUfB6uLFdfNmaXLRNaRs6w4GI9ZDwnuVWAgQ3uajWnUTigq1gXbKGcI4G4Es8cBKZsVQhxsKzOqLFGXDONbQEX_00000000000000",
"productEnsembleId" : "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"date" : "2019/11/01",
"status" : "En cours",
"col2_data" : [
{
"_id" : "5da8948e877c34001529a7f2",
"id" : "8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166",
"name" : "ensemble 2",
"image" : "fjO9sb3FUmDFhgWn49v1Io5Oa5sdFyL7KZRVzsH0n06n7GtNqIPdFSfDT67BSIvfYSmdTh7IoYyize3SDX169cas4MWMwVWLsF989ZWy76ANsYS4tkLS5OYR1i2TrqXjP40WDCcWvr6OkQapgzuk4hAISx7Mwf6Wp2Z3krzjn72PrTXUDmG7nDrp7VKDrsonCVqkmGs7lAwocdEeghWs7NUVkMdIGMjWDVo8u3wlClzs2e5X_00001571329177",
"produits" : null
}
]
}
which is a combination of collection 1 and collection 2. If you want all records from collection 1 simply remove the $match criteria.
Edit: Include PHP version of same query above...
To use this query in a PHP page see below. This example assumes using the latest MongoDB driver and strategies including using PHP Composer...
<?php
require 'vendor/autoload.php';
$client = new MongoDB\Client('mongodb://johndoe:mypassword#localhost:27017');
$collection = $client->ensemble->col1;
$cursor = $collection->aggregate(
array(
array( '$match' => array( '_id' => '5db8683c877c34001559f192' ) ),
array(
'$lookup' => array(
'from' => 'col2',
'localField' => 'productEnsembleId',
'foreignField' => 'id',
'as' => 'col2_data'
)
)
)
);
foreach($cursor as $document) {
print_r($document);
}
?>
PHP Results:
MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[_id] => 5db8683c877c34001559f192
[id] => 1BuVJCLGIUIcDXfBQVlpzccAP6r2JRQPGL4wHTEfPildnnWU5gUh8oymfJM2a6wOW117sTbzWJGKLNaRCZ7uMNHA2CnBjT4PeM44B9QaNYMZfg1BiiBa5JYBRLxMLxFTOY88PDFm4U4yDn9iPnljRnfeqpu9ZBl7fGS4tnnlmuz2ntlXb6cFFrFmQIo8EpDOwr5LLyaSrI67mLUya94WMUnDOojXpf4UAjcmMTayM4x9fmla_00001572366396
[userId] => DEXpMPBstW37YkixF5e6yPeVpkElumYN1nyw0rjjcPy6vf8mdUHXzIg8KMvy0KegxThD5LgKS6WnuhvPwbLqa3aoyhVgIOhk0huqvxmQ0ctBFMVZZyaPkADdGmWUFM10OhTo919uQOb4QgZLZjtDOnTkcmLUfB6uLFdfNmaXLRNaRs6w4GI9ZDwnuVWAgQ3uajWnUTigq1gXbKGcI4G4Es8cBKZsVQhxsKzOqLFGXDONbQEX_00000000000000
[productEnsembleId] => 8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166
[date] => 2019/11/01
[status] => En cours
[col2_data] => MongoDB\Model\BSONArray Object
(
[storage:ArrayObject:private] => Array
(
[0] => MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[_id] => 5da8948e877c34001529a7f2
[id] => 8FMOBUO8TArv0PcyQ2GSDhGPWRxMjMSLtCOcRV21G04yoCKq1i3POwPqEWwj6wJoeydY28thZMWmO4uP7Yha2xNMV1m0zmjfqtZgsKmTA1Qghku3I0rekTJ51cH2XlXan4zUV5hjjEolRWjREOR7N9DD9sCvoQF2kr3EhI553RYIdwgivRtYJYH4g6oqVv2nrob3KbrLwd95MbNnzwmCqGNM20q0zgF8HUJjCxIfphNyVcwO_00001571329166
[name] => ensemble 2
[image] => fjO9sb3FUmDFhgWn49v1Io5Oa5sdFyL7KZRVzsH0n06n7GtNqIPdFSfDT67BSIvfYSmdTh7IoYyize3SDX169cas4MWMwVWLsF989ZWy76ANsYS4tkLS5OYR1i2TrqXjP40WDCcWvr6OkQapgzuk4hAISx7Mwf6Wp2Z3krzjn72PrTXUDmG7nDrp7VKDrsonCVqkmGs7lAwocdEeghWs7NUVkMdIGMjWDVo8u3wlClzs2e5X_00001571329177
[produits] =>
)
)
)
)
)
)

PHP json array manipulation

I have a JSON array like this:
{
result:{
customers:[
{
customer_id:16096,
customer_name:"test#test.test",
customer_login_name:"******",
customer_login_pwd:"*****",
customer_active:0,
customer_register_date:"2018-07-20 10:48:22",
customer_dashboard_email:"******",
customer_dashboard_pwd:"******",
used:"0.00",
name:"Trial",
price:0,
bandwidth:1,
start_date:"2018-07-20",
end_date:"2018-07-27",
package_is_active:1
},
{
customer_id:16648,
customer_name:"asd#asd.asd",
customer_login_name:"******",
customer_login_pwd:"********",
customer_active:1,
customer_register_date:"2018-08-08 17:24:16",
customer_dashboard_email:"******#*******.com",
customer_dashboard_pwd:"******",
used:"0.00",
name:"Trial",
price:0,
bandwidth:1,
start_date:"2018-08-08",
end_date:"2018-08-15",
package_is_active:1
},
{
customer_id:15271,
customer_name:"MarioRossiTEST",
customer_login_name:"mario#test.test",
customer_login_pwd:"*****",
customer_active:0,
customer_register_date:"2018-06-22 11:36:42",
customer_dashboard_email:"*****#******.com",
customer_dashboard_pwd:"*******",
used:"0.00",
name:"Trial",
price:0,
bandwidth:1,
start_date:"2018-06-22",
end_date:"2018-06-30",
package_is_active:0
},
]
}
}
Now in PHP i would like to provide the "customer_name" and retreive the "customer_id" of the same customer.
For example i provide "test#test.test" and i would like to get "16096".
Any way i could do this?
EDIT: After decoding the JSON array to PHP:
If you are doing this very often, I would suggest for looping through the array and creating a dictionary with the "customer_name" value as the key and the "customer_id", "customer_login_name", etc. in a dictionary that's the value to the "customer_name" key.
$customers_dic = {
"test#test.test"=> {
customer_id => 16096,
customer_login_name => "******",
customer_login_pwd =>"*****",
customer_active => 0,
customer_register_date => "2018-07-20 10:48:22",
customer_dashboard_email => "******",
customer_dashboard_pwd => "******",
used => "0.00",
name => "Trial",
price => 0,
bandwidth => 1,
start_date => "2018-07-20",
end_date => "2018-07-27",
package_is_active => 1
},
"asd#asd.asd" => {
customer_id => 16648,
customer_login_name => "******",
customer_login_pwd => "********",
customer_active => 1,
customer_register_date => "2018-08-08 17:24:16",
customer_dashboard_email => "******#*******.com",
customer_dashboard_pwd => "******",
used => "0.00",
name => "Trial",
price => 0,
bandwidth => 1,
start_date => "2018-08-08",
end_date => "2018-08-15",
package_is_active => 1
},
"mario#test.test" => {
customer_id => 15271,
customer_name => "MarioRossiTEST",
customer_login_pwd => "*****",
customer_active => 0,
customer_register_date => "2018-06-22 11:36:42",
customer_dashboard_email => "*****#******.com",
customer_dashboard_pwd => "*******",
used => "0.00",
name => "Trial",
price => 0,
bandwidth => 1,
start_date => "2018-06-22",
end_date => "2018-06-30",
package_is_active => 0
},
}
This way you can quickly access any "customer_id" by going $customers_dic["some#customer.name"]["customer_id"].
If you are just doing this a small number of times, you can just for loop through the customers array, keeping track of the index and checking if you have arrived on the desired customer's name.
$desired_customer_id;
for ($i = 0; $i < count($customers); $i++) {
if ($customers[$i]["customer_name"] === $desired_customer_name) {
$desired_customer_id = $customers[$i]["customer_id"];
}
}
You could also do this with a foreach instead; choice is up to you. :)
http://php.net/manual/en/function.json-decode.php
$arr = json_decode($json, true);
then you need to find your customer
array_filter($arr['result']['customers'], function ($customer) {
return ($customer['customer_name'] === 'test#test.test')
});
http://php.net/manual/en/function.array-filter.php

How to use the function inside the json_decode() using ci

Here i have one array, in this array i have one more array called studentabsentId,
public function admin_getabsentlist()
{
$data = array(
"schoolId" => $_POST['schoolName'],
"classId" => $_POST['className'],
"sectionId" => $_POST['sectionName'],
"absentDate" => date("Y-m-d", strtotime($_POST['absentDate']))
);
$absentresponse= $this->Admin_attendance_model->admin_options_listdisplay($data);
$optionsList = array();
foreach($absentresponse as $hmres)
{
$hmparent['studentabsentId']=json_decode($hmres['studentAbsentId']);
$hmparent['studentAbsentDate']=$hmres['studentAbsentDate'];
array_push($optionsList,$hmparent);
}
//echo $json = json_encode($optionsList);
$return = array("status" => 1, "data" => $optionsList);
echo json_encode($return);
}
echo json_encode($return);
{
"status": 1,
"data": [
{
"studentabsentId": [
"1"
],
"studentAbsentDate": "2017-04-12"
}
]
}
upto now its working fine,now what i want means,studentabsentId 1 means what is his name,suppose studentabsentId 2 means what is name, for that purpose i written the function called getStudentnameById in helper/custom_helper.php.
So in my for each loop i added one more line like this
$hmparent['studentabsentName']=json_decode(getStudentnameById($hmres['studentAbsentId']));
But now i am getting the error of Undefined offset: 0,how can solve this error and , how to display the name
custom_helper.php
if ( ! function_exists('getStudentnameById')){
function getStudentnameById($id){
$ci =& get_instance();
$ci->load->database();
$ci->db->select('firstName');
$ci->db->where('student_id', $id);
$q = $ci->db->get('new_student')->result();
return $q[0]->firstName; // particulart filed
}
}
My updated code
print_r($absentresponse);
Array
(
[0] => Array
(
[absendId] => 2
[studentAbsentId] => ["1"]
[studentAbsentDate] => 2017-04-12
[schoolId] => 2
[classId] => 1
[sectionId] => 1
[reg_date] => 2017-04-13 01:01:14
[created_by] => kanniyappan#g2evolution.co.in
[status] => 0
)
)
Expected Results
{
"status": 1,
"data": [
{
"studentabsentId":"1"
"studentabsentName":"Kani"
"studentAbsentDate": "2017-04-12"
}
]
}
Your getStudentnameById returns a string supposedly, so why are you doing a json_decode on top of that. $hmparent['studentabsentName']=json_decode(getStudentnameById($hmres['studentAbsentId']));
Also check the return by that function. You should be able to debug this kind of code if you turned on your error_reporting which tells you the line at which error occurred, then var_dump all the variables that's relevant to it.

How to generate a pass from 2 different json_encodes

I use this method to generate a pass: public function setJSON($JSON) {
if(json_decode($JSON) !== false) {
$this->JSON = $JSON;
return true;
}
$this->sError = 'This is not a JSON string.';
return false;
}
I call this method to generate pass by: $pass->setJSON('{
"passTypeIdentifier": "'.$passTypeID.'",
"formatVersion": 1,
..............
"barcode": {
"altText" : "'.$alt.'",
"format" : "PKBarcodeFormatPDF417",
"message": "Member-Card",
"messageEncoding": "iso-8859-1",
"changeMessage" : "This pass now has altText %# !"
},
"locations" : [
{
"longitude" : 104.89529371261597,
"latitude" : 11.576150037278605,
"relevantText": "CamMob (dis. 1%)"
},
.....................
]
}');
But now I don't write those locations statically and I get those data from database by : $query5 = mysql_query("select * from company");
while ($row5 = mysql_fetch_array($query5)){
$companyName = $row5['relevantTextName'];
$discount = $row5['relevantTextDiscount'];
$long = $row5['longitute'];
$lat = $row5['latitute'];
$link = $row5['link'];
$location['locations'][] = array("longitute" => $long, "latitute" => $lat, "relevantText" => $companyName." (" . $discount. "%)" );
}
$jsonString = json_encode($location) ;
error_log("Locations: ".$jsonString,0);
$pass->setJSON($jsonString);
$pass->setJSON('{
"passTypeIdentifier": "'.$passTypeID.'",
"barcode": {
"altText" : "'.$alt.'",
"format" : "PKBarcodeFormatPDF417",
"message": "Member-Card",
"messageEncoding": "iso-8859-1",
"changeMessage" : "This pass now has altText %# !"
}
}');</pre>
There is no error when I test for updating pass, but I cannot see the pass on lock screen like before. Thus it means that I not yet include those locations to the pass. What should I change ? Is it the problem of method setJSON ? If I do like this, how can I combine these 2 jsons to become together ?
Rather than constructing the JSON directly, construct an array first, then transform it into JSON.
$pass_data = array("passTypeIdentifier" => $passTypeID,
"formatVersion" => 1,
"barcode" => array (
"altText" => $alt,
"format" => "PKBarcodeFormatPDF417",
"message" => "Member-Card",
"messageEncoding" => "utf-8", // use UTF8 in case you want to encode Khmer or other non ASCII
"changeMessage" => "This pass now has altText %# !"
),
"locations" => $locationsArray,
"organizationName" => "Digi club card",
"description" => "Membership card",
"logoText" => "Digiclub",
"foregroundColor" => "rgb(0,0,0)",
"backgroundColor" => "rgb(211,211,211)",
"generic" => array (
"headerFields" => array(
array ( "key" => "Status",
"label" => " ",
"value" => "Membership card"
),
),
"primaryFields" => array(
array ( "key" => "Name",
"value" => $memberName,
),
),
"secondaryFields" => array(
// Secondary Field data
),
"auxiliaryFields" => array(
// Auxiliary Field data
),
"backFields" => array(
// Backfiels Field data
),
)
);
Then transform the array into JSON:
$pass->setJSON(json_encode($pass_data));

Categories