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);
Related
Hey i have five json from all getting information now i encountered with problem like this -> from five different json i need to get latest videoId who newer shows first and all it need put to one function foreach for my too hard i try it do about 5hours and stay in same step
Json 1 json 2
All code need from this two json get latest(newest) videoId in one foreach echo
<?php
$videoList1 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCKLObxxmmAN4bBXdRtdqEJA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'));
$videoList2 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCynfZM0Edr9cA4pDymb2rEA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'));
$i = 0;
foreach($videoList1->items as $item){
if(isset($item->id->videoId)) {
echo $item->id->videoId;
if ( ++$i > 3) {
break;
}
}
}
Tray this:
$videoList1 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCKLObxxmmAN4bBXdRtdqEJA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'),true);
$videoList2 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCynfZM0Edr9cA4pDymb2rEA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'),true);
$videoList = array_merge($videoList1["items"],$videoList2["items"]);
/// sort lastet first
foreach ($videoList as $key => $part) {
$sort[$key] = strtotime($part['snippet']['publishedAt']);
}
array_multisort($sort, SORT_DESC, $videoList);
foreach ($videoList as $video) {
if(isset($video["id"]["videoId"])) {
echo 'publishedAt: '. $video['snippet']['publishedAt'] . ' VideoID: ' . $video["id"]["videoId"] . "\n </br>";
}
}
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.
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/>';
}
I try to request an array of IDs, to return each row with that ID, and push each into an Array $finalArray
But only the first result from the Query will output, and at the second foreach, it skips the while loop.
I have this working in another script, so I don't understand where it's going wrong.
The $arrayItems is an array containing: "home, info"
$finalArray = array();
foreach ($arrayItems as $UID_get)
{
$Query = "SELECT *
FROM items
WHERE (uid = '" . cleanQuery($UID_get) . "' )
ORDER BY uid";
if($Result = $mysqli->query($Query))
{
print_r($UID_get);
echo "<BR><-><BR>";
while ($Row = $Result->fetch_assoc())
{
array_push($finalArray , $Row);
print_r($finalArray );
echo "<BR><><BR>";
}
}
else
{
echo '{ "returned" : "FAIL" }'; //. mysqli_connect_errno() . ' ' . mysqli_connect_error() . "<BR>";
}
}
(the cleanQuery is to escape and stripslashes)
What I'm trying to get is an array of multiple rows (after i json_encoded it, like:
{ "finalArray" :
{ "home":
{ "id":"1",
"created":"0000-00-00 00:00:00",
"css": "{ \"background-color\" : \"red\" }"
}
},
{ "info":
{ "id":"2",
"created":"0000-00-00 00:00:00",
"css":"{ \"background-color\" : \"blue\" }"
}
}
}
But that's after I get both, or more results from the db.
the print_r($UID_get); does print info, but then nothing..
So, why am I not getting the second row from info? I am essentially re-querying foreach $arrayItem right?
Turns out... The leading space in the array, for the second item had to be trimmed with:
trim($UID_get);
Thanks GBD
after fetching array from mysql resource, try executing the following function, by passing fetched array as parameter.(inside your while loop)
function array_remove_indexes(&$arr)
{
$new_arr = array();
foreach($arr as $name => $val)
{
if(!is_int($name))$new_arr[$name]=$val;
}
$arr = $new_arr;
}
I have a PDO Query that returns what appears to be an array $pds. I can loop through this array as follows:
foreach ($pds as $row) {
}
I need to loop through the same array a second time but when I do this there doesn't appear to be any data in the array. Also I've tried to copy the array as follows:
$pds2 = $pds;
Is there a trick I'm missing to use this array twice?
thx
Code:
// Remove Duplicate Locations where words are in a different order
$cityArray = $pds;
foreach ($cityArray as $data) {
$words = explode(' ', $data['city'] . ' ' . $data['region1'] . ' ' . $data['region2'] . ' ' . $data['region3']);
sort($words);
$cityWordsArray[$data['id']] = implode(' ', $words);
}
$cityWordsArray = array_unique($cityWordsArray);
foreach ($pds as $row) {
echo 'hi';
foreach($cityWordsArray as $key=>$value) {
if($row['id'] == $key) {
I'm afraid that $pds is not an array, but a PDOStatement.
If you want to get as an array, you should use fetchAll to get the result as an array.
Try $pds = $pds->fetchAll(); before the loop.