Optimization PHP - php

I have a code like this:
$res = array ();
$i2 = 0;
for ($i = 0; $i <10; $i++) {
if ($table ['users'] [$i] ['value'] == null) {
break;
}
$res ['users'] [$i2] ['value'] = $table ['users'] [$i] ['value'];
$res ['users'] [$i2] ['user_id'] = $table ['users'] [$i] ['user_id'];
$res ['users'] [$i2] ['name'] = $table ['users'] [$i] ['name'];
$i2 ++;
}
$mesto;
for ($i3 = 0; $i3 <count ($table ['users']); $i3 ++) {
if ($user_id == $table ['users'] [$ i3] ['user_id']) {
$mesto = $ i3 + 1;
break;
}
}
$res ['currentTop'] = $mesto;
$json = json_encode ($res, JSON_UNESCAPED_UNICODE);
echo $json;
$table * - This is decoded json, table has an array users, in which objects, each with three fields * value, user_id, name *
JSON looks like this:
{
"users": [{
"value": "994954359439",
"user_id": 2,
"name": "Anton Piskorskyi"
}, {
"value": 99999,
"user_id": 99999,
"name": "Anton Piskorskyi"
}, {
"value": 99998,
"user_id": 99998,
"name": "Anton Piskorskyi"
}, {
"value": 99997,
"user_id": 99997,
"name": "Anton Piskorskyi"
}, {
"value": 99996,
"user_id": 99996,
"name": "Anton Piskorskyi"
}, {
"value": 99995,
"user_id": 99995,
"name": "Anton Piskorskyi"
}, {
"value": 99994,
"user_id": 99994,
"name": "Anton Piskorskyi"
}, {
"value": 99993,
"user_id": 99993,
"name": "Anton Piskorskyi"
}, {
"value": 99992,
"user_id": 99992,
"name": "Anton Piskorskyi"
}, {
"value": 99991,
"user_id": 99991,
"name": "Anton Piskorskyi"
}]
}
Themselves such objects can be 100,000 or more. The above code takes the first 10 objects from the array and by * user_id * looks for the index of the object in which this * user_id * is located. In short, the code is used to display the top 10 players and the current position of the user. Those. this piece of code will be called quite a few times in a small amount of time. I have intel I3-71 on my computer ... and when I start spamming the opening of the page many times, the processor is loaded by ~ 50% (this is for 100,000 objects), if you put this code on the VDS, then with a large online VDS can not to export, hence the question arises: how can all this be optimized? namely this function:
$mesto;
for ($i3 = 0; $i3 <count ($table ['users']); $i3 ++) {
if ($user_id == $table ['users'] [$i3] ['user_id']) {
$mesto = $i3 + 1;
break;
}
}
P.S.*
Objects I call this in Json:
{
"value": "994954359439",
"user_id": 2,
"name": "Anton Piskorskyi"
}

Related

Array for subseries on highcharts Drilldown

I'm having some problems generating graphs with drilldown in Highcharts.
I'm using Highcharts to render a pie with drilldown series.
I need to transform this output json
Drilldownseries = [
{
"name": "LAZIO",
"data": [["ROMA", 28]],
"id": "LAZIO"
},
{
"name": "LAZIO",
"data": [["FROSINONE", 218]],
"id": "LAZIO"
},
{
"name": "LAZIO",
"data": [["LATINA", 212]],
"id": "LAZIO"
},
{
"name": "TOSCANA",
"data": [["FIRENZE", 2]],
"id": "TOSCANA"
},
{
"name": "TOSCANA",
"data": [["LIVORNO", 5]],
"id": "TOSCANA"
},
{
"name": "TOSCANA",
"data": [["PISA", 9]],
"id": "TOSCANA"
}
];
to
Drilldownseries = [
{
"name": "LAZIO",
"data": [["ROMA", 28], ["FROSINONE", 218], ["LATINA", 212]],
"id": "LAZIO"
},
{
"name": "TOSCANA",
"data": [["FIRENZE", 2], ["LIVORNO", 5], ["PISA", 9]],
"id": "TOSCANA"
}
];
This is the part of query that populates the array:
...
if($res3)
{
$i = 0;
while ($row = mysqli_fetch_array($res3, MYSQLI_ASSOC))
{
$row3[$i]["name"] = $row["name"];
$row3[$i]["data"] = [[$row["subname"],$row["data"]]];
$row3[$i]["id"] = $row["id"];
$i++;
};
$row3 = json_encode($row3,JSON_NUMERIC_CHECK);
};
I'd prefer to extract the array with php well formed, but should be the same tranform the json.
PHP 7.2
Highcharts 6.1.1
for benefit of all, this is my solution. Code refined should be appreciated :)
First removed square brackets in code below
$row3[$i]["data"] = [$row["subname"],$row["data"]];
then create the new array so
$repl = array();
$i = 0;
foreach ($row3 as $value) {
if (!isset($repl[$i]['id'])) {
$repl[$i]['id'] = $value['id'];
$repl[$i]['name'] = $value['name'];
$repl[$i]['data'] = [$value['data']];
} elseif (($repl[$i]['id']) <>$value['id']) {
$i++;
$repl[$i]['id'] = $value['id'];
$repl[$i]['name'] = $value['name'];
$repl[$i]['data'] = [$value['data']];
} else {
array_push($repl[$i]['data'], $value['data']);
}
}
$resultx = json_encode($repl,JSON_NUMERIC_CHECK);
thanks

Sort JSON by ID

I have following JSON file:
[{
"id": 9,
"title": "Birthday",
"description": "Debut Party",
"start": "2017-07-25T15:01",
"end": "2017-08-03T00:01",
"url": "https:\/\/bd.com"
}, {
"id": 11,
"title": "Anniversary",
"description": "First Ann",
"start": "2017-06-28T15:00",
"end": "2017-07-08T02:58",
"url": "https:\/\/anniversary.com\/"
}, {
"id": 5,
"title": "Anniversary",
"description": "First Ann",
"start": "2017-06-28T15:00",
"end": "2017-07-08T02:58",
"url": "https:\/\/anniversary.com\/"
}]
I want them to be sorted by id like 5,9,11 using PHP. How Can I do that?
First decode the JSON
$array = json_decode($json,true);
and then use usort to sort by id or something else.
function sortById($a, $b) {
return $b->id - $a->id;
}
usort($array,"sortById");
SELECT * FROM test ORDER BY `id` DESC;
use this query in you php file.
example :
function getPosts()
{
$connection = mysqli_connect("localhost", "root", "", DatabaseManager::DATABASE_NAME);
$sqlQuery = "SELECT * FROM posts order by 'id' desc;";
$result = $connection->query($sqlQuery);
$postsArray = array();
if ($result->num_rows > 0) {
for ($i = 0; $i < $result->num_rows; $i++) {
$postsArray[$i] = $result->fetch_assoc();
}
}
echo json_encode($postsArray);
}

How to Count Number of in in a field

I have a data base named nominator which has some fields
it have a in field named 'noinatedUnder' how can i show the number of inS to that field
this is the Raw text of
SELECT FROM Nominator
{
"result": [
{
"#type": "d",
"#rid": "#73:2",
"#version": 2,
"#class": "Nominator",
"isTemp": "true",
"id": "JJRXW",
"Email": "testuser#test.com",
"Name": "nijeesh",
"Phone": "7894561234",
"school": "#65:2",
"in_noinatedUnder": [
"#161:1",
"#162:1",
"#163:1",
"#164:0",
"#165:0",
"#166:0",
"#167:0",
"#168:0",
"#161:0",
"#162:0",
"#163:0"
],
"#fieldTypes": "school=x,in_noinatedUnder=g"
},
{
"#type": "d",
"#rid": "#74:0",
"#version": 1,
"#class": "Nominator",
"isTemp": "true",
"id": "SU7SV",
"Email": "npms#school.com",
"Name": "pon muthu",
"Phone": "7778455215",
"school": "#65:2",
"#fieldTypes": "school=x"
},
{
"#type": "d",
"#rid": "#75:1",
"#version": 1,
"#class": "Nominator",
"isTemp": "true",
"id": "4DZ86",
"Email": "sivaraj#testschool.com",
"Name": "sivaraj",
"Phone": "7788899445",
"school": "#65:2",
"#fieldTypes": "school=x"
},
{
"#type": "d",
"#rid": "#76:1",
"#version": 1,
"#class": "Nominator",
"isTemp": "true",
"id": "HFQJ1",
"Email": "klndk#knvd.com",
"Name": "dbhbsd",
"Phone": "8656548745",
"school": "#65:2",
"#fieldTypes": "school=x"
}
],
"notification": "Query executed in 6.12 sec. Returned 4 record(s)"
}
in this on the first entry there is 11 entrys in the in->nominated under area and 0 on everything else how to select this number using sql for each field
that is it should print
-----------
count | ----------
11
0
0
0
i did got the result using php
$query = "select * from `Nominator`";
$result = runquery($query);
$a = array();
for($i=0;$i<sizeof($result);$i++)
{
echo '<p>';
echo isset($result[$i]->oData->in_noinatedUnder)?sizeof($result[$i]->oData->in_noinatedUnder):0;
echo '</p>';
}
function runquery($query)
{
$client = new PhpOrient();
$client->hostname = 'localhost';
$client->port = 2424;
$client->username = 'root';
$client->password = 'hello';
$client->connect();
$client->dbOpen('tabe');
$result = $client->query($query);
$json = json_decode(json_encode($result));
if (sizeof($json) > 0) {
return $json;
} else {
return false;
}
}
So is there any way to get the count directly from sql it self, like select count(*) from nominator gives count of nominators
To get the number of vertexes in in try this query:
select in().size() from <class-name>
Hope it helps.
Regards

How to combine multiple SQL queries into one to output as JSON in PHP code?

I currently have the following table set up:
StartTime EndTime Performer Event Day Location
-----------------------------------------------------
1:00pm 2:00pm Test Test 0 1
11:00pm 12:00am Test Test 0 0
2:00pm 2:30pm Test Test 1 0
11:00pm 12:00am Test Test 2 1
The JSON output looks something like this:
{
"day0": {
"item1": {
"StartTime": "1:00pm",
"EndTime": "2:00pm",
"Performer": "Test",
"Event": "Test",
"Location": 1
},
"item2": {
"StartTime": "11:00pm",
"EndTime": "12:00am",
"Performer": "Test",
"Event": "Test",
"Location": 0
}
},
"day1": {
"item1": {
"StartTime": "2:00pm",
"EndTime": "2:30pm",
"Performer": "Test",
"Event": "Test",
"Location": 0
}
},
"day2": {
"item1": {
"StartTime": "11:00pm",
"EndTime": "12:00am",
"Performer": "Test",
"Event": "Test",
"Location": 1
}
}
}
Since I'm still learning PHP, I wrote some sloppy code by making 3 queries to the database, each time selecting all data where the day was 1, 2, and 3.
Here's an example of code for fetching data for day=0, which is repeated for day=1 and day=2:
echo '{ "day0" : {';
$sql = "select * from table WHERE day = 0";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$jsonData = array();
$rowCount = $result->num_rows;
$index = 1;
while($row =mysqli_fetch_assoc($result))
{
echo '"item'.$index.'":';
echo json_encode(array("StartTime" => $row['StartTime'], "EndTime" => $row['EndTime'], "Performer" => $row['Performer'], "Event" => $row['Event'], "Location" => intval($row['Location'])));
if ($rowCount != $index)
{
echo ',';
}
++$index;
}
echo ' }';
// Repeated code for day=1
// Repeated code for day=2
echo ' }';
I feel as though this can be achieved with just one query, but being that I'm new, I'm not sure how to implement it.
I started to do something like this:
$sql = "select * from table";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$jsonData = array();
$numOfRows = $result->num_rows;
$count = 1;
while($row = mysqli_fetch_assoc($result))
{
$outerIndex = 'day'.$row['day'];
if ($row['day'] == '1')
{
// Do something, not sure
}
if ( !isset( $jsonData[$outerIndex] ) )
{
$innerIndex = 'item'.$count.'';
$jsonData[$outerIndex][$innerIndex] = $row;
}
++$count;
}
echo json_encode($jsonData);
However, I just got stuck, and not really sure how to approach it further.
SQL:
$sql = "SELECT * FROM table ORDER BY Day";
Further down on code:
$result_object = [];
$item = 1;
while ($row = $result->fetch_assoc()) {
if(isset($result_object['day'.$row['Day']]))
{
$result_object['day'.$row['Day']]['item'.$item] = $row;
$item++;
}
else
{
$result_object['day'.$row['Day']]['item1'] = $row;
$item = 2;
}
}
You can then output it with:
echo json_encode($result_object, JSON_PRETTY_PRINT); //JSON_PRETTTY_PRINT is not necessary...
You may disagree with me, but I don't think indexing items with item0, item1 and so on.... or day0, day1 ... is a GOOD idea. I personally prefer that the looping through the result would be:
while ($row = $result->fetch_assoc()) {
if(isset($result_object[$row['Day']]))
{
$result_object[$row['Day']]->items[] = $row;
}
else
{
$result_object[$row['Day']] = (object)['day'=>$row['Day'], 'items'=>[$row]];
}
}
In this case, the result would be an array of objects. ie:
[
{
"day": "0",
"items": [
{
"StartTime": "07:23:56",
"EndTime": "17:24:04",
"Performer": "Performer1",
"Event": "Event1",
"Day": "0",
"Location": "1"
},
{
"StartTime": "09:24:30",
"EndTime": "01:04:37",
"Performer": "Performer2",
"Event": "Event2",
"Day": "0",
"Location": "1"
}
]
},
{
"day": "1",
"items": [
{
"StartTime": "10:25:22",
"EndTime": "11:25:29",
"Performer": "Performer2",
"Event": "Event3",
"Day": "1",
"Location": "2"
}
]
},
{
"day": "2",
"items": [
{
"StartTime": "12:26:08",
"EndTime": "13:26:12",
"Performer": "Performer3",
"Event": "Event4",
"Day": "2",
"Location": "1"
}
]
}
]
The reason: you can easily iterate through each values(an array) in whatever language you're going to use.

JSON array in array from SQL database using PHP

I have the following code:
$retarray = array();
$hoursarray = array();
$res = $this->mysqli->query("SELECT id, title, groupby FROM scheduler_activity WHERE gewerbe = '$this->gewerbe'");
while($row = $res->fetch_object()) {
$foo = $this->mysqli->query("SELECT dow, start, end FROM scheduler_businesshours WHERE activity = '$row->id'");
while($hours = $foo->fetch_object()){
$hoursarray[] = $hours;
}
$retarray[] = $row;
$retarray["businessHours"] = $hoursarray;
}
return $retarray;
And the following JSON output:
{
"0": {
"id": "1",
"title": "Spinning",
"groupby": "Trainingsgruppe"
},
"businessHours": [{
"dow": "[1,2,3]",
"start": "17:00:00",
"end": "18:00:00"
}, {
"dow": "[4,5]",
"start": "17:30:00",
"end": "18:30:00"
}],
"1": {
"id": "2",
"title": "Massage",
"groupby": "Trainingsgruppe"
},
"2": {
"id": "3",
"title": "Yoga",
"groupby": "Trainingsgruppe"
},
"3": {
"id": "4",
"title": "Dance Academy",
"groupby": "Trainingsgruppe"
}
}
So far it looks correct but I need to get rid of the leading numbers like 0, 1, 2, 3
That it will look like this plus the businessHours:
[{
"id": "1",
"title": "Spinning",
"groupby": "Trainingsgruppe"
}, {
"id": "2",
"title": "Massage",
"groupby": "Trainingsgruppe"
}, {
"id": "3",
"title": "Yoga",
"groupby": "Trainingsgruppe"
}, {
"id": "4",
"title": "Dance Academy",
"groupby": "Trainingsgruppe"
}]
What did I do wrong there?
Thank you!
As I understood about your code, we get business hour for each activity, so it's just a small change at line 10:
$retarray = array();
$hoursarray = array();
$res = $this->mysqli->query("SELECT id, title, groupby FROM scheduler_activity WHERE gewerbe = '$this->gewerbe'");
while($row = $res->fetch_object()) {
$foo = $this->mysqli->query("SELECT dow, start, end FROM scheduler_businesshours WHERE activity = '$row->id'");
while($hours = $foo->fetch_object()){
$hoursarray[] = $hours;
}
$row["businessHours"] = $hoursarray; // Change to this, swap line 10 & 11
$retarray[] = $row;
}
return $retarray;
Hope this helps.
You add two keys. One key is numeric the second is businessHours.
$retarray[] = $row;
$retarray["businessHours"] = $hoursarray;
For instance you can add it businessHours to $row
$row["businessHours"] = $hoursarray;
$retarray[] = $row;
Have you try array_values($array)?
$retarray = array();
$hoursarray = array();
$res = $this->mysqli->query("SELECT id, title, groupby FROM scheduler_activity WHERE gewerbe = '$this->gewerbe'");
while($row = $res->fetch_object()) {
$foo = $this->mysqli->query("SELECT dow, start, end FROM scheduler_businesshours WHERE activity = '$row->id'");
while($hours = $foo->fetch_object()){
$hoursarray[] = $hours;
}
$retarray[] = $row;
$retarray["businessHours"] = $hoursarray;
}
return array_values($retarray);

Categories