I am working on parsing HTML and get multidimensional output array as json.
I am parsing html like I want but I couldn't create JSON array.
The example output of foreach loop:
PS: every json object has different string value.
0:"blahblah"
1:"blahblah"
2:"blahblah"
3:"blahblah"
4:" " // only space
5:"blahblah"
6:"blahblah"
7:"blahblah"
8:"blahblah"
9:" " // only space
...
I want create json array like this:
$output = array();
$html = str_get_html($ret);
$lessons["lesson"] =array();
foreach($html->find('table//tbody//tr') as $element) {
$temp = strip_tags($element->innertext);
array_push($lessons['lesson'], $temp); // the objects (I wrote as 'blahblah' every object but I getting different values always)
if($temp == " ") // if there is only space push array the output and create new array
{
array_push($output , $lessons["lesson"]);
unset($lessons);
$lessons["lesson"] = array();
}
}
echo (json_encode($output ,JSON_UNESCAPED_UNICODE)); // $output show nothing
Thanks in advice.
If your issue is getting all the blah into the array then the below will get you there. I am not following the code too well but attempt to explain my thoughts in comments.
$json = ["blahblah"
,"blahblah"
,"blahblah"
,"blahblah"
," "
,"blahblah"
,"blahblah"
,"blahblah"
,"blahblah"
," "];
$lessons["lesson"] = []; // I think this is the array you are using
$tmp = []; // Something tmp to hold things
foreach($json as $elm){ //Loop what I assume $html->find('table//tbody//tr') is returning
if($elm != ' '){//Wait for a ' ' and add to tmp
$tmp[] = $elm;
} else {
$lessons["lesson"][] = $tmp; // This array is done so keep it and restart
$tmp = [];
}
}
Related
So I would like to create just one loop to parse the json data i have. I can successfully parse it in 2 foreach loops however when trying to combine in one loop using $key => $value the $key returns nothing when called. How can I successfully take the 2 foreach loops I have here and combine them into one?
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key) {
$GenreID = $key['id'].'<br>';
echo $GenreID;
}
foreach($jsonList as $key => $value) {
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
The json data is as follows:
{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":10751,"name":"Family"},{"id":14,"name":"Fantasy"},{"id":36,"name":"History"},{"id":27,"name":"Horror"},{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10770,"name":"TV Movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}
You can still use $key as an index when also extracting the $value.
However note that you shouldn't be assigning the line breaks to your variables, and should instead consider them part of the view by echoing them out independently:
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key => $value) {
$GenreID = $key['id']; // Depending on structure, you may need $value['id'];
$GenreName = $value['name'];
echo $GenreID . '<br>';
echo $GenreName . '<br><br>';
}
Your single loop below here.
foreach($jsonList as $key)
{
$GenreID = $key['id'].'<br>';
echo $GenreID;
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
$key is a assosative array.Therefore it had some index.So you can use this index in single loop.
It seems you get confused over your data structure. Seeing the json, the resulting "$jsonlist" supposed to contain array with id and value as keys.
You can iterate over it and extract the the appropriate key.
Myabe something like this:
foreach($jsonlist as $value) {
echo "id: " . $value['id'] . "\n";
echo "name: " . $value['name'] . "\n";
}
extra bonus, if you want to create 1 level array from your json based on id with the name you could try array reduce using anon function like this:
$jsonlist = array_reduce($jsonlist, function($result, $item){
$result[$item['id']] = $item['name'];
return $result;
}, []);
extra neat for transformation of static structure data.
This it´s my little script, but don´t get right results at the moment :
<?php
// Delimiters betweeb data "*" elements in each data delimiters ","
$data_string="house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";
// Explode $data_string for "~" delimiter
$data_exp=explode("*",$data_string);
//
// Loop 1
foreach($data_exp as $data_1)
{
$data_exp_compar=explode(",",$data_1);
// We want see the elements with the same data in common in second position (403,404,etc)
$data_common_1[]=$data_exp_compar[1];
$data_common_2[]=$data_exp_compar[1];
}
$a=array_values(array_intersect_key($data_common_1,$data_common_2));
$b=array_count_values(array_intersect_key($data_common_1,$data_common_2));
foreach($a as $aa=>$values)
{
echo $aa;
print "<br>";
}
?>
The idea in this script. It scans the data inside "$data_string", as you can see, all data delimiters is "*" and inside each data we have elements with "," as delimiter
I want get this output results and in this format :
PRODUCT Id: 403 (2 Actually)
1- house1,403,phone1
2- house3,403,phone3
PRODUCT Id: 404 (1 Actually)
1 - house2,404,phone2
Product Id: 405 (1 Actually)
1 - house4,405,phone4
As you can see the only element for compare it´s in the second position and it´s product´s id
I try many things but i can´t get works, or get finally results as i want show
Thank´s in advanced for all , regards
You can group them first then another foreach loop for printing result
$data_string="house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";
$data_exp = explode("*",$data_string);
$group = []; // Initialize group array
foreach($data_exp as $data_1)
{
$data_exp_compar=explode(",",$data_1);
$group[$data_exp_compar[1]][] = $data_exp_compar; // Group by the number key after exploding
}
// Loop to each group, then print desired format
foreach ($group as $key => $value) {
echo 'Product ID: ' . $key . ' (' . count($value) . ' Actually)<br>';
foreach ($value as $k => $v) {
echo ++$k . ' - ' . implode(',', $v) . '<br>';
}
echo '<br>';
}
I would suggest using array_map and array_filter functions. Let me know if you have questions about this.
<?php
// Prepare data and input
$id = 403;
$data = "house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";
// Convert string data to array
$data = explode("*", $data);
$data = array_map(function ($row) {
return explode(",", $row);
}, $data);
// Search the array
$response = array_filter($data, function ($row) use ($id) {
return $row[1] == $id;
});
print_r($response);
I'm on PHP and I need to edit a JSON output to return only objects >=0 and divided by one hundred
Eg.
$json = {"data":[0,55,78,-32,-46,37]}
Needed
$json = {"data":[0,0.55,0.78,0.37]}
How this can be done?
Well, I know this is not the best practice, but if it's as simple as this, you can do the following.
$json = '{"data":[0,55,78,-32,-46,37]}';
// decoding the string to objects & arrays
$x = json_decode($json);
// applying a function on each value of the array
$x->data = array_map(
function($a)
{
if( $a >= 0 ) return $a/100;
else return null;
},
$x->data
);
// Removing empty values of the array
$x->data = array_filter($x->data);
// making a JSON array
$jsonData = json_encode(array_values($x->data));
// inserting a JSON array in a JSON Object
$json = '{"data":' . $jsonData . '}';
// here is your {"data":[0,0.55,0.78,0.37]}
echo $json;
Hope it helps !
Btw, I had to trick the json encode with array_values to prevent the creation of an object rather than an array for the data content. But I guess there is a better method that I just don't know ...
EDIT :
Find out the way :D
Once empty values removed from the array, just do :
$x->data = array_values($x->data);
$json = json_encode($x);
This will do the trick and it will not create issues with the rest of the object.
Alessandro:
Here's my approach, feel free to try. json_decode and a simple foreach can help you...
Code:
$json = array();
$result = array();
$json = '{"data":[0,55,78,-32,-46,37]}';
$decoded_json=json_decode($json, TRUE);
foreach ($decoded_json['data'] as &$value) {
if ($value >= 0){
$value = $value / 100;
$result[]=$value;
}
}
echo json_encode($result);
?>
Result:
[0,
0.55,
0.78,
0.37
]
I am using a URL to fetch data stored/shown within URL. I get all the value of variable using $_REQUEST['v_name'] but if there is a array in URL how can i retrieve that value.
For Example:
WWW.example.com/rooms?&hid=213421&type=E
I got the value hid and type using
$hid=$_REQUEST['hid'];
but in URL like:
WWW.example.com/rooms?&rooms=2&rooms[0].adults=2&rooms[0].children=0&rooms[1].adults=2&rooms[1].children=0
how can i retrieve value of adults and children in each room.
please help.
Thanks in Advance
You could also try something like this, since most of your original $_REQUEST isn't really an array (because of the .s in between each key/value pair):
<?php
$original_string = rawurldecode($_SERVER["QUERY_STRING"]);
$original_string_split = preg_split('/&/', $original_string);
$rooms = array();
foreach ($original_string_split as $split_one) {
$splits_two[] = preg_split('/\./', $split_one);
}
foreach ($splits_two as $split_two) {
if (isset($split_two[0]) && isset($split_two[1])) {
$split_three = preg_split('/=/', $split_two[1]);
if (isset($split_three[0]) && isset($split_three[1])) {
$rooms[$split_two[0]][$split_three[0]] = $split_three[1];
}
}
}
// Print the output if you want:
print '<pre>' . print_r($rooms, 1) . '</pre>';
$valuse = $_GET;
foreach ($valuse as $key=>$value)
{
echo $key .'='. $value. '<br/>';
}
When converting a MongoCursor to PHP I use this script. Which was presented here
StackOverflowSO
using the upper method, the structure is same but _id is whereas using the lower script which yields the below included result.
Unfortunately, this results in the actual object being embedded into an array with the _id from Mongo. Like this :
`4eefa79d76d6fd8b50000007 = {
"_id" = {
"$id" = 4eefa79d76d6fd8b50000007;
};
longText = "Error Description";
nCode = dee29fd7e15ce4ab2d3f7dfa7c5d8fc44b27501ad00908771128c920ef276154;
nStatus = Process;
nText = "E12345";
nVType = Type1;
pId = {
"$id" = 4eefa79676d6fd8b50000003;
};
pushDate = "2011-12-20+06%3A07%3A41";
updateFlag = 1;
};`
Since I am passing this object to another service for processing the _id is not known.
How can I convince the PHP Driver to parse the object properly?
Basically what I did was this.
return json_encode(iterator_to_array($cursor));
But this created the aforementioned object which is not what I needed.
I solved it in this way.
$i=0;
foreach($cursor as $item){
$return[$i] = array(
'_id'=>$item['_id'],
'nCode'=>$item['nCode'],
'pId'=>$item['pId'],
'nText'=>$item['nText'],
'longText'=>$item['longText'],
'nStatus'=>$item['nStatus'],
'nVType'=>$item['nVType'],
'pushDate'=>$item['pushDate'],
'updateFlag'=>$item['updateFlag'],
'counter' => $i
);
$i++;
}
return json_encode($return);
If you result is big in order to save RAM you could try this more efficient method:
function outIterator($iterator, $resultName='results')
{
// Efficient MongoCursor Iterator to JSON
// instead of encoding the whole result array to json
// process each item individually
// in order to save memory by not copying the data multiple times
//Start Json Output
header('Content-Type: application/json');
echo '{' . $resultName . ': ['
//Output each item as json if there are results in the iterator
if ($iterator->hasNext()){
foreach ($iterator as $item)
{
echo json_encode ($fixeditem);
if ($iterator->hasNext()) echo ', ';
}
}
//end Json output
echo ']}';
}
$results = $db->collection->find();
outIterator($results);