remove first or specific child node xpath - php

this code get table.
I want to remove first and second tr tag in the table.
$data = array();
$table_rows = $xpath->query('//table[#class="adminlist"]/tr');
if($table_rows->length <= 0) { // exit if not found
echo 'no table rows found';
exit;
}
foreach($table_rows as $tr) { // foreach row
$row = $tr->childNodes;
if($row->item(0)->tagName != 'tblhead') { // avoid headers
$data[] = array(
'Name' =>trim($row->item(0)->nodeValue),
'LivePrice' => trim($row->item(2)->nodeValue),
'Change'=> trim($row->item(4)->nodeValue),
'Lowest'=> trim($row->item(6)->nodeValue),
'Topest'=> trim($row->item(8)->nodeValue),
'Time'=> trim($row->item(10)->nodeValue),
);
}
}
and question 2
In the bellow table tr have two class --- EvenRow_Print and OddRow_Print ---
$data = array();
$table_rows = $xpath->query('//table/tr');
if($table_rows->length <= 0) {
echo 'no table rows found';
exit;
}
foreach($table_rows as $tr) { // foreach row
$row = $tr->childNodes;
if($row->item(0)->tagName != 'tblhead') { // avoid headers
$data[] = array(
'Name' =>trim($row->item(0)->nodeValue),
'LivePrice' => trim($row->item(2)->nodeValue),
'Change'=> trim($row->item(4)->nodeValue),
'Lowest'=> trim($row->item(6)->nodeValue),
'Topest'=> trim($row->item(8)->nodeValue),
'Time'=> trim($row->item(10)->nodeValue),
);
}
}
How can I echo both tr in one 2d array .
examp.
Array(
[0] => Array(
//array
)
}
Thank's

For question 1 - there are different ways to skip the first and last element, e.g. removing the first entry using array_shift() and the last entry using array_pop(). But as it's not clear if it'd be better to keep the array as it is, it's possible to skip both entries in the foreach in an easy way like using a counter, continuing for the first entry and breaking for the last:
$i = 0;
$trlength = count($table_rows);
foreach( ...) {
if ($i == 0) // is true for the first entry
{
$i++; // increment counter
continue; // continue with next entry
}
else if ($i == $trlength - 1) // last entry, -1 because $i starts from 0
{
break; // exit foreach loop
}
.... // handle all other entries
$i++; // increment counter in foreach loop
}

Related

Expand (json) object in 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;
}

Array Showing Values from previous iteration

I have this code using an api , the first iteration is showing everything right , but at the second iteration is showing the items from the first iteration + the items from the second iteration , and the same thing at the third iteration.
I dont want that , how can i fix that problem ?
$g=0;
foreach ($matches as $match) {
$inside = $api->getMatch('123');
$pp = $api->getMatchTimeline('123');
foreach ($inside->participants as $partId) {
if ($partId->championId == $match->champion) {
$participant_id[] = $partId->participantId;
$participant_idS = $partId->stats->participantId;
foreach ($pp->frames as $p) {
foreach ($p->events as $t) {
if ($t->type == "ITEM_PURCHASED" and $t->participantId == $participant_idS) {
$item_id = $t->itemId;
$d = $api->getStaticItem($item_id);
if($d->depth == 2 or $d->depth == 3){
$itemsMade[] = $d->id;
}
}
}
}
}
}
$dt = [['match_ids' => $part, "champion" => $soloq->champion, "timestamp" => $match->timestamp, "participantId" => $participant_id[$g++], "itens" => json_encode($itemsMade)]
];
echo ' <pre>';
var_dump($dt);
echo '</pre>';
}
You need to set that array to be empty at the start of your loop. Otherwise you just keep adding to it as you see in your output.
foreach ($inside->participants as $partId) {
$itemsMade = [];

Collect duplicate data in array using php

this is my sample array data from bio-metrics
I just want to collect data that has the same bio_id and date
temp:[
0:{
bio_id:"1"
date:"2017-10-05"
date_time:"2017-10-05 08:00:22"
device_name:"biometrics"
time:"08:00:22"
}
1:{
bio_id:"1"
date:"2017-10-05"
date_time:"2017-10-05 08:00:23"
device_name:"biometrics"
time:"08:00:23"
}
2:{
bio_id:"2"
date:"2017-10-05"
date_time:"2017-10-05 08:06:29"
device_name:"biometrics"
time:"08:06:29"
}
3:{
bio_id:"1"
date:"2017-10-05"
date_time:"2017-10-05 15:06:47"
device_name:"biometrics"
time:"15:06:47"
}
4:{
bio_id:"2"
date:"2017-10-05"
date_time:"2017-10-05 16:01:50"
device_name:"biometrics"
time:"16:01:50"
}
]
I been stuck with this code that I made, and don't know how I should manipulate it, or how I will store it properly, I have try some array function but it gives different result to my data
$len = count($temp);
for ($i=0; $i <$len ; $i++) {
$id = $temp[$i]['bio_id'];
$date = $temp[$i]['date'];
for ($x=0; $x < $len; $x++) {
if ($id == $temp[$x]['bio_id'] && $date == $temp[$x]['date']) {
$data[] = $temp[$x];
$int[] = $x;
}
}
}
I don't know how I should manipulate it, or how I will store it properly, I have try some array function but it gives different result to my data
This code will work to collect duplicate in the array on the basis of id and date
$newTemp = array();
foreach($temp as $value){
$newTemp[$value['id'].'_'.$value['date']][] = $value;
}
$newTemp = array();
for($temp as $value){
$key = $value->id." ".$value->date;
if(isset($newTemp[$key])){
$newTemp[$key] = array_merge($newTemp[$key],$value);
}else{
$newTemp[$key] = $value;
}
}
I just want to collect data that has the same bio_id and date
The easiest way is to iterate over the input array and aggregate the data into a new array, indexed by key generated using the bio_id and date fields. This way, a duplicate entry can be easily identified because the key already exists in the output array.
$input = array(/* the big input array here */);
// Build the output here
$output = array();
foreach ($input as $item) {
$key = $item['bio_id'].':'.$item['date'];
if (array_key_exists($key, $output)) {
// This is a duplicate
// Ignore the data, update only the count
$output[$key]['count'] ++;
} else {
// This is the first time this combination is processed
// Copy the input
$output[$key] = $item;
// Keep in 'count' how many times this combination exists in the input
$output[$key]['count'] = 1;
}
}
Each entry of $output is the first entry of $input that has the same combination of bio_id and date. Additional, the value of count is the number of entries of $input that share that pair of bio_id and date.
Work on this example if you need to aggregate the data in a different way (keep all duplicates, instead of their number, f.e.).
Another example that keeps the duplicates:
// Build the output here
$output = array();
foreach ($input as $item) {
$key = $item['bio_id'].':'.$item['date'];
if (array_key_exists($key, $output)) {
// This is a duplicate; add it to the list
$output[$key]['all'][] = $item;
} else {
// This is the first time this combination is processed
// Copy important values (bio_id and date) from the input
$output[$key] = array(
'bio_id' => $item['bio_id'],
'date' => $item['date'],
// Store the entire $item into a list
'all' => array($item),
);
}
}
Read about PHP arrays how to access their elements using the square brackets syntax and how to create or modify their values.

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

How to build a tree view with PHP / SQL?

What's the best way to:
Get the data from the db using a single query
Loop through the results building e.g. a nested unordered list
My table has id, name and parent_id columns.
Here's an update to my last answer, with a counter that gives each ul a nesting 'level' class, and some comments.
Could anyone suggest how to adapt this to use table rows, without nesting, but with some kind of class numbering hierarchy for css/js hooks?
<?
//
// Get the data
//
include_once("inc/config.php");
$query = "SELECT c.*
FROM categories AS c
ORDER BY c.id
LIMIT 1000";
$result = pg_query($db, $query);
//
// Load all the results into the row array
//
while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC))
{
//
// Wrap the row array in a parent array, using the id as they key
// Load the row values into the new parent array
//
$categories[$row['id']] = array(
'id' => $row['id'],
'description' => $row['description'],
'parent_id' => $row['parent_id']
);
}
// print '<pre>';
// print_r($category_array);
// ----------------------------------------------------------------
//
// Create a function to generate a nested view of an array (looping through each array item)
// From: http://68kb.googlecode.com/svn-history/r172/trunk/upload/includes/application/controllers/admin/utility.php
//
function generate_tree_list($array, $parent = 0, $level = 0)
{
//
// Reset the flag each time the function is called
//
$has_children = false;
//
// Loop through each item of the list array
//
foreach($array as $key => $value)
{
//
// For the first run, get the first item with a parent_id of 0 (= root category)
// (or whatever id is passed to the function)
//
// For every subsequent run, look for items with a parent_id matching the current item's key (id)
// (eg. get all items with a parent_id of 2)
//
// This will return false (stop) when it find no more matching items/children
//
// If this array item's parent_id value is the same as that passed to the function
// eg. [parent_id] => 0 == $parent = 0 (true)
// eg. [parent_id] => 20 == $parent = 0 (false)
//
if ($value['parent_id'] == $parent)
{
//
// Only print the wrapper ('<ul>') if this is the first child (otherwise just print the item)
// Will be false each time the function is called again
//
if ($has_children === false)
{
//
// Switch the flag, start the list wrapper, increase the level count
//
$has_children = true;
echo '<ul class="level-' . $level . '">';
$level++;
}
//
// Print the list item
//
echo '<li>' . $value['description'] . '';
//
// Repeat function, using the current item's key (id) as the parent_id argument
// Gives us a nested list of subcategories
//
generate_tree_list($array, $key, $level);
//
// Close the item
//
echo '</li>';
}
}
//
// If we opened the wrapper above, close it.
//
if ($has_children === true) echo '</ul>';
}
// ----------------------------------------------------------------
//
// generate list
//
generate_tree_list($categories);
?>
function generate_list($array,$parent,$level)
{
foreach ($array as $value)
{
$has_children=false;
if ($value['parent_id']==$parent)
{
if ($has_children==false)
{
$has_children=true;
echo '<ul>';
}
echo '<li>'.$value['member_name'].' -- '.$value['id'].' -- '.$value['parent_id'];
generate_list($array,$value['id'],$level);
echo '</li>';
}
if ($has_children==true) echo '</ul>';
echo $value['parent_id'];
}
}
MySQL have created a good article on this subject: Managing Hierarchical Data in MySQL
You can create a breadcrumb view style by using arrays, without using a recursive function.
Here is my working code:
First, make a SQL query like this:
$category = CHtml::listData(TblCategory::model()->findAllCategory(array(
'distinct'=>true,
'join'=>'LEFT JOIN tbl_category b on b.id = t.cat_parent',
'join'=>'LEFT JOIN tbl_category c on c.cat_parent = 0',
'order' => 'cat_name')),'id','cat_name');
I am using yii related code so you can use normal join queries, then form an array in a foreach() function
public function findAllCategory($condition='',$params=array())
{
Yii::trace(get_class($this).'.findAll()','system.db.ar.CActiveRecord');
$criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
$category = array();
$cat_before;
$parent_id = array();
$cat_before = $this->query($criteria,true);
//echo "<br><br><br><br><br><br><br>";
foreach($cat_before as $key => $val)
{
$category[$key] = $val;
$parent_id[$key]['cat_parent'] =$val['cat_parent'];
$parent_id[$key]['cat_name'] =$val['cat_name'];
foreach($parent_id as $key_1=> $val_1)
{
if($parent_id[$key]['cat_parent'] == $category[$key_1]['id'])
{
$category[$key]['cat_name']= $category[$key_1]['cat_name'] .' > '. $parent_id[$key]['cat_name'];
}
}
}
return $cat_before;
}
Then you can get result using Main cat >> subcat 1 >> subcat_1 inner >> ...

Categories