I am trying to compare a JSON return with set ARRAY.
The JSON is showing OK, this is set as $a.
The ARRAY is coded and is showing OK, this is set as $b.
I'd like the output to be a percentage, not including duplicates.
THIS IS NOW EDITED.
<?php
$loggedUser = auth()->user()->id ; // returns authenticated user id.
$pdo = new PDO('mysql:host=****;dbname=****', '****', '****');
$stmt = $pdo->prepare('SELECT movie_id FROM user_watch_lists WHERE user_id = :user');
$stmt->execute(array('user' => $loggedUser));
$result_array = $stmt->fetchAll(PDO::FETCH_ASSOC);
$a = $result_array;
$b = array(297761);
print_r($a);
print_r($b);
$c = 0;
foreach ($a as $k=>$v) {
if ($v == $b[$k]) $c++;
}
echo ($c/count($a))*100;
?>
Contents of the return above (echo $a; and $echo b; and echo ($c/count($a))*100;):
Array ( [0] => Array ( [movie_id] => 297761 ) )
Array ( [0] => 297761 )
0
This should return 100%. I can see why, but unsure how to fix.
I've tried to change the loop to go in to the array but get ERROR.
foreach ($a as $r=>$k=>$v) {
if ($v == $b[$k]) $c++;
}
echo ($c/count($a))*100;
Related
I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:
one json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}.
I will be getting another JSON which ever edited from admin panel. for example if i updated any key, only that key will coming in the
second JSON --> for ex: {"blog_heading":"def"}
Now, i have to replace the value of second json to first json. example output for above scenario like I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:
output json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"def"}.
So i am trying as below,
$id = json_decode($data_string);
$id2 = json_encode($post);
$id5 = json_decode($id2);
$id6 = array();
foreach ($id as $key => $value)
{
$log->debug($key . ': ' . $value);
if (array_key_exists($key, $id5->data)) {
$log->debug($key . 'element is in the array');
$log->debug($value . 'element is in the array');
//array_push($id5, "apple", "raspberry");
$id3 = array($key => $value);
$id3[$key] = $value;
$log->debug($id3);
}else{
$log->debug($key . 'element is not in the array');
}
}
$id7 = json_encode($id2);
$log->debug($id7);
id5 data is : $id5
DEBUG - 2017-06-05T02:26:20-04:00 - stdClass Object
(
[meta] => stdClass Object
(
[table] => story
[type] => item
)
[data] => stdClass Object
(
[id] => 7
[active] => 1
[blogId] => abc
[blog_heading] => xyz
)
)
==================
Log of $id :
stdClass Object
(
[active] => 1
[blog_heading] => def
[id] => 7
)
Please suggest me how can i achieve this... Anything i am doing wrong here
Please try that:
$j1 = '{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}';
$j2 = '{"blog_heading":"def"}';
$result = json_encode(
array_merge(
json_decode($j1, true),
json_decode($j2, true)
)
);
<?php
$json1='{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}';
$json2='{"blog_heading":"def"}';
$json1=json_decode($json1);
$json2=json_decode($json2);
foreach ($json1 as $key => $value) {
if($json2->$key){
$json1->$key=$json2->$key;
}
}
$json1=json_encode($json1);
$json2=json_encode($json2);
If you have only one element in array,Do like this
$a = json_decode('{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}',true);
$b = json_decode('{"blog_heading":"def"}',true);
$a['blog_heading'] = $b['blog_heading'];
print_r($a);
If you have multiple element like this :
$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"blog_heading":"def"},{"blog_heading":"hello"}]',true);
$return = array();
for ($i=0; $i < count($c); $i++) {
$c[$i]['blog_heading'] = $d[$i]['blog_heading'];
$return[] = $c[$i];
}
print_r($return);
If you want to replace value by specific id
$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"id":7,"blog_heading":"def"},{"id":9,"blog_heading":"hello"}]',true);
$return = array();
for ($i=0; $i < count($c); $i++) {
if($d[$i]['id'] == $c[$i]['id']) {
$c[$i]['blog_heading'] = $d[$i]['blog_heading'];
}
$return[] = $c[$i];
}
print_r($return);
Checking dynamic key value pair :
$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"id":6,"blog_heading":"def"},{"id":9,"blog_heading":"hello"}]',true);
$return = array();
for ($i=0; $i < count($c); $i++) {
$result = array_intersect_key($c[$i], $d[$i]);
foreach ($result as $key => $value) {
$c[$i][$key] = $d[$i][$key];
}
$return[] = $c[$i];
}
print_r($return);
Check demo here
I have an array of json as shown below and i want to sort it by size
Array
(
[0] => {"file_name":"Desert - Copy.jpg","content_type":"image\/jpeg","tmp_path":"\/var\/www\/mywebsite.com\/public_html\/www\/tmp\/0000000012","sha256":"010f60d2927a35d0235490136ef9f4953b7ee453073794bcaf153d20a64544ea","size":"845941"}
[1] => {"file_name":"Hydrangeas - Copy.jpg","content_type":"image\/jpeg","tmp_path":"\/var\/www\/mywebsite.com\/public_html\/www\/tmp\/0000000013","sha256":"3b92fede080f9b0ec902afc58831191b5b8ccbaf6732352fd7a8b445d1e9f0bd","size":"595284"}
[2] => {"file_name":"Tulips.jpg","content_type":"image\/jpeg","tmp_path":"\/var\/www\/mywebsite.com\/public_html\/www\/tmp\/0000000014","sha256":"b9352f2565260219db72fc1fc896113a26c85866b69c50d3970c4d9f5cce830a","size":"620888"}
)
Result expected:
Array
(
[0] => {"file_name":"Hydrangeas - Copy.jpg","content_type":"image\/jpeg","tmp_path":"\/var\/www\/mywebsite.com\/public_html\/www\/tmp\/0000000013","sha256":"3b92fede080f9b0ec902afc58831191b5b8ccbaf6732352fd7a8b445d1e9f0bd","size":"595284"}
[1] => {"file_name":"Tulips.jpg","content_type":"image\/jpeg","tmp_path":"\/var\/www\/mywebsite.com\/public_html\/www\/tmp\/0000000014","sha256":"b9352f2565260219db72fc1fc896113a26c85866b69c50d3970c4d9f5cce830a","size":"620888"}
[2] => {"file_name":"Desert - Copy.jpg","content_type":"image\/jpeg","tmp_path":"\/var\/www\/mywebsite.com\/public_html\/www\/tmp\/0000000012","sha256":"010f60d2927a35d0235490136ef9f4953b7ee453073794bcaf153d20a64544ea","size":"845941"}
)
How do i accomplish this in an efficient manner
<?php
function sortByYear($a, $b) {
$dA = new DateTime($a['date']);
$dB = new DateTime($b['date']);
return $dA->format('y') - $dB->format('y');
}
$data = '{"info":[{"id":1, "title":"original title", "name":"john doe", "date":"2010-05-15"}, {"id":2, "title":"another title", "name":"foo bar", "date":"2009-04-11"}]}';
$d = json_decode($data, true);
$info = $d['info'];
usort($info, 'sortByYear');
print_r($info);
?>
source:http://codepad.org/6N4fmbKG
You should read this for further help:How to sort a JSON array with PHP
Here is what i came up with but i welcome more efficient solutions
function sort_json($json_array)
{
if (count($json_array) > 1) {
//convert to array
foreach ($json_array as &$json) {
$array[] = json_decode($json);
}
// sort in ascending order by size
usort($array, function($a, $b)
{
return $a->size < $b->size ? -1 : 1; //Compare the sizes
});
//convert back to json
$json_array = array();
foreach ($array as &$a) {
$json_array[] = json_encode($a);
}
}
return $json_array;
}
Use the following code:
function sortBySize($a, $b)
{
if ($a['size'] == $b['size']) return 0;
return ($a['size'] < $b['size']) ? -1 : 1;
}
usort($data, "sortBySize");
How usort work : http://www.w3schools.com/php/func_array_usort.asp
I am new to php just playing with some array.
I Want to get following things from the array which are of different dimensional
The following is the Multidimensional Array
$a = array(
array(
'productsid' => 90,
'CouponID' => 50
),
array(
'productsid' => 80,
'CouponID' => 95
),
array(
'productsid' => 80,
'CouponID' => 95
));
The following is Single dimensional array:
$b = array(80,90,95);
I want to compare only the productsid index of the array with the single dimensional array and wants to fetch the data which is equal to it.
I Have tried the following loop to print but it only gives the values of the productsid only but I want that full array. But only by comparing the Productid with the second array.
for ($i = 0; $i < 3; $i++) {
foreach ($a[$i] as $key => $value) {
foreach ($b as $c) {
if ($value == $c) {
echo $value .'<br>';
}
}
} }
Looks like you're looking for in_array():
$result = array();
foreach($a as $item)
if(in_array($item['productsid'], $b))
$result []= $item;
or, in a more concise (but less readable IMO) way:
$result = array_filter($a, function($item) use($b) {
return in_array($item['productsid'], $b);
});
For your test data it's doesn't matter much, but if your arrays are big and/or this loop is going to run many times, you can achieve better performance by converting the lookup array into a hash table and using O(1) key lookup instead of linear array search:
$bs = array_flip($b);
$result = array_filter($a, function($item) use($bs) {
return isset($bs[$item['productsid']]);
});
$b = array(80,90,95);
$c = array();
foreach($a as $val) {
if(in_array($val['productsid'],$b)) {
$c[] = $val;
}
}
echo "<pre>";
print_r($c);
Try this:
foreach($a as $ar) {
if (in_array($ar['productsid'], $b))
print_r($ar);
}
i am using PDO to get some values of a table like : (table name is ban)
ID word
1 one
2 two
3 three
4 four
MY function is :
function retBans() {
global $connect;
$result = $connect->prepare("SELECT * FROM ban");
$result->execute();
$a = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$a = $row['word'].",";
}
return $a;
}
and in the main php file, i wanted to get them back with this code :
$a = array();
$a = retBans();
$b = explode(",",$a);
print_r($b);
I wanted to have this :
Array {
[0] => one
[1] => two
[2] => three
[3] => four
}
But , it just return and print_r the last value (four) in array.
How can i get them like i said ?
Use this instead -
$a = '';
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$a .= $row['word'].",";
}
Then, you can use explode function
$a = retBans();
$b = explode(",",$a);
echo "<pre>"; print_r($b);
Ok I'm seriously stuck, I've been working on a nav menu that I just cannot get to function how I want it to so i've changed tack but am now stuck again so any help would be much appreciated and desperately needed!
I have the code below and am trying to do the following - I have an array that holds info for all the pages of a site and then another array that holds the ids of the pages that are child pages. What I want to do is use a foreach loop to loop through all the pages of the first array and check whether their ids are in the array of child ids or not. If they are not then they are top level nav pages and I want to output some code and then set up another foreach loop which will check whether any subpages have a parent id of the current page and so on.
I can't seem to work out how to compare $b with the ids in the $childpages array no matter what I try! Is this even possible and if so how please?
This is the first section of what im trying at present
<?php function buildMenu4 ($allpages, $childpages) {
foreach ($allpages as $pages){
$a = $pages['parentid'];
$b = $pages['id'];
$c = $childpages;
echo "<ul>\n";
if (!in_array($b, $c)) {
DO SOMETHING..........
Array contents of $c:
Array
(
[0] => Array ( [id] => 6 )
[1] => Array ( [id] => 15 )
[2] => Array ( [id] => 100 )
[3] => Array ( [id] => 101 )
[4] => Array ( [id] => 103 )
[5] => Array ( [id] => 104 )
[6] => Array ( [id] => 105 )
)
edit ---------------------------------
I have reworked my code and am back to a variation of where I was a couple of days ago!! Anyway the code below works as intended until I try to loop it and then it just echoes the results of the first foreach loop e.g. foreach ($allpages as $pages){..... but fails to do anything else.
I am trying to make a function called loopMenu and then run this recursively until there are no more pages to be displayed. I have tried to write the function as shown with the pusedo code in the code block below but I just can't get it to work. I may have muddled up some of the arguments or parameters or perhaps I have just made a big mistake somewhere but I can't see it - any help would be hugely appreciated and desperately needed!
<?php function buildMenu6 ($allpages, $childpageids, $childpages, $subchildpages) {
foreach ($childpageids as $childid){
$c[] = $childid['id'];
};
echo "<ul>\n";
foreach ($allpages as $pages){
$a = $pages['parentid'];
$b = $pages['id'];
if (!in_array($b, $c)){
echo "<li>" . $pages['linklabel'] . "";
WHERE I WANT THE FUNCTION TO START E.G. function loopMenu($childpages, $subchildpages){...the code that follows....
echo"<ul>\n";
foreach ($childpages as $childparent) {
$d = $childparent['parentid'];
$e = $childparent['id'];
if (($d == $b) or ($d == $g)) {
echo "<li>" . $childparent['linklabel'] . "";
echo "<ul>\n";
foreach ($subchildpages as $subchild){
$g = $subchild['id'];
$f = $subchild['parentid'];
if ($f == $e){
echo "<li>" . $subchild['linklabel'] . "";
WHERE I TRY TO RERUN THE FUNCTION USING loopMenu($childparent, $subchild);
echo "<li/>";
};
};
echo"</ul>\n";
echo "</li>";
};
};
echo "</ul>\n";
WHERE I WANT MY FUNCTION TO END E.G. };
echo "</li>";
};
};
echo "</ul>\n";
}; ?>
Then I call the main buildMenu6 function like so:
<?php buildMenu6($pageids, $childPageIds, $childPageArray, $childPageArray); ?>
You need a nested foreach (I've changed your var names or used the original ones for readability):
foreach($allpages as $page) {
foreach($childpages as $child) {
if($page['id'] == $child['id']) {
//do something
break;
}
}
}
Or PHP >= 5.5.0 use array_column:
$childids = array_column($childpages, 'id');
foreach($allpages as $page) {
if(in_array($page['id'], $childids)) {
//do something
}
}
As a kind of hybrid:
foreach($childpages as $child) {
$childids[] = $child['id'];
}
foreach($allpages as $page) {
if(in_array($page['id'], $childids)) {
//do something
}
}
foreach ($allpages as $pages){
$a = $pages['parentid'];
$b = $pages['id'];
$c = $childpages;
echo "<ul>\n";
// In array isn't aware of the 'id' keys
$found = false;
foreach ($c as $id => $value) {
if ($value == $b) {
$found = true;
}
}
if ($found) {
// DO SOMETHING
}
according to THIS SO ANSWER, array_key_exists is (marginally) the fastest array lookup for php.
since, from your description, it seems reasonable to suppose that [id] is a PRIMARY key and, therefore, unique, i would change the [id] dimension and put values directly in its lieu:
$c[105] = NULL; // or include some value, link page URL
... // some code
$needle = 105;
... // some more code
if (array_key_exists($needle,$c)) {
instead of
$c[5] = 105; // $c is the haystack
... // some code
$needle = 105;
... // some more code
foreach ($c as $tempValue) {
if ($tempValue == $needle) {
in case you want to put values in $c, then you could also use isset (it will return FALSE if array value is NULL for said key).