I have the an array, in which I store one value from the database like this:
$stmt = $dbh->prepare("SELECT token FROM advertisement_clicks WHERE (username=:username OR ip=:ipcheck)");
$stmt->bindParam(":username",$userdata["username"]);
$stmt->bindParam(":ipcheck",$ipcheck);
$stmt->execute();
$data = array();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
So, that gives me: array("token","token");
When I print it:
Array ( [0] => Array ( [token] => 677E2114AA26BA4351A686917652C7E1BA67A32D ) [1] => Array ( [token] => C42190F3D72C5BB6BB6B68488D1D4662A8D2A138 ) )
I then have a loop, that loops all the tokens. In that loop, I try to search for a specific token, and if it that token matches, it will be marked as "seen":
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return $key;
}
}
}
This is my loop:
$icon = "not-seen";
foreach($d as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam == $token){
$icon = "seen";
}
}
However, searchForid() simply returns 0
What am I doing wrong?
Ok, here you can see a PHP fiddle that works
$data = array();
$data[] = array('token'=>'123');
$data[] = array('token'=>'456');
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return true;
}
}
return false;
}
$icon = "not-seen";
foreach($data as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam){
$icon = "seen";
}
}
echo $icon;
It echos 'seen' which is expected since I compare the same array values, now assuming that your $d variable has different tokens, it should still work this way.
That means that your $d array does not contain what you claim it contains, could you print_r this variable and post it in your answer?
Related
I'm trying to parse JSON data in the format [{code:SE rate:1.294},{code:UK rate:2.353}] from this page:
http://www.mycurrency.net/service/rates
I have implemented an IP reader that detects the users location in a 2 letter country code. I want to pluck the correct data from that link with 'code' and return the value 'rate'. I was thinking I might have to do a foreach loop to iterate through all the countries?
This is my code, I hope this is what are you looking for.
First I create a new array $output to make it more easy to search
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
After that we use a function to search value in array and returning the key. I got it from here
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
and then I run the function with the first parameter as country code to get the keys of specific country code.
$find = searchForRate("BT", $output);
And then echo the rates from our $output array by key in $find variable
echo 'RATE = '.$output[$find]['rate'];
This is the complete codes
<?php
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
$find = searchForRate("BT", $output);
echo 'RATE = '.$output[$find]['rate'];
Example output:
RATE = 64.13
Suppose, i have the fallowing json:
{
"foo.bar": 1
}
and i want to save this like this:
$array["foo"]["bar"] = 1
but i also can have more than 2 "parameters" in string. For example:
{
"foo.bar.another_foo.another_bar": 1
}
and i want to save this same way.
$array["foo"]["bar"]["another_foo"]["another_bar"] = 1
Any ideas how can i do that in case that i don't know how many parameters i have?
This is far from the nicest solution, but I've been programming all day so I'm a little tired, but I hope it gives you something to work off, or at least a working solution for the time being.
Here's the IDEone of it working: click
And here's the code:
$json = '{
"foo.bar": 1
}';
$decoded = json_decode($json, true);
$data = array();
foreach ($decoded as $key => $value) {
$keys = explode('.', $key);
$data[] = buildNestedArray($keys, $value);
}
print_r($data);
function buildNestedArray($keys, $value) {
$new = array();
foreach ($keys as $key) {
if (empty($new)) {
$new[$key] = $value;
} else {
array_walk_recursive($new, function(&$item) use ($key, $value) {
if ($item === $value) {
$item = array($key => $value);
}
});
}
}
return $new;
}
Output:
Array
(
[0] => Array
(
[foo] => Array
(
[bar] => 1
)
)
)
Wasn't sure whether your JSON string could have multiples or not so I made it handle the former.
Hope it helps, may come back and clean it up a bit in the future.
Start with a json_decode
Then build a foreach loop to break apart the keys and pass them to some kind of recursive function that creates the values.
$old_stuff = json_decode($json_string);
$new_stuff = array();
foreach ($old_stuff AS $key => $value)
{
$parts = explode('.', $key);
create_parts($new_stuff, $parts, $value);
}
Then write your recursive function:
function create_parts(&$new_stuff, $parts, $value)
{
$part = array_shift($parts);
if (!array_key_exists($part, $new_stuff)
{
$new_stuff[$part] = array();
}
if (!empty($parts)
{
create_parts($new_stuff[$part], $parts, $value);
}
else
{
$new_stuff = $value;
}
}
I have not tested this code so don't expect to just cut and past but the strategy should work. Notice that $new_stuff is passed by reference to the recursive function. This is very important.
Try the following trick for "reformatting" into json string which will fit the expected array structure:
$json = '{
"foo.bar.another_foo.another_bar": 1
}';
$decoded = json_decode($json, TRUE);
$new_json = "{";
$key = key($decoded);
$keys = explode('.', $key);
$final_value = $decoded[$key];
$len = count($keys);
foreach ($keys as $k => $v) {
if ($k == 0) {
$new_json .= "\"$v\"";
} else {
$new_json .= ":{\"$v\"";
}
if ($k == $len - 1) $new_json .= ":$final_value";
}
$new_json .= str_repeat("}", $len);
var_dump($new_json); // '{"foo":{"bar":{"another_foo":{"another_bar":1}}}}'
$new_arr = json_decode($new_json, true);
var_dump($new_arr);
// the output:
array (size=1)
'foo' =>
array (size=1)
'bar' =>
array (size=1)
'another_foo' =>
array (size=1)
'another_bar' => int 1
I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?
Maybe you could use the array_udiff_assoc() function with a callback
Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);
First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)
I found a way to search my multidimensional array and output the result and it works, however it only finds the first match and stops. If I have more than one match in the array I want to be able to show them all.
My array looks like this (the first layer of keys goes from 0, 1, 2 etc):
Array
(
[0] => Array
(
[mydevice] => blahblah
[ipadd] => 10.10.10.209
[portnum] => 16040
)
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return null;
}
$myoutput = searcharray($ptn2, mydevice, $newresult);
I can then echo the results using something like $newresult[$myoutput][mydevice].
However if I have more than one entry in the array with a matching data in the 'mydevice' key it doesn't return them (just the first one).
That is because return breaks the function. You could use something like this:
function searcharray($value, $key, $array) {
$result = array();
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
$result[] = $k;
}
}
return $result;
}
Now you will always get an array as result - empty if nothing was found. You can work with this like this e.g.
$mydevicekeys = searcharray($ptn2, "mydevice", $newresult);
foreach ($mydevicekeys as $mydevicekey) {
// work with $newresult[ $mydevicekey ]["mydevice"]
}
So add the results to an array :)
function searcharray($value, $key, $array) {
$res = array();
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
$res[] = $key;
}
}
return $res;
}
I have a database table with a column where multiple strings are stored in each field, separated by a ;
I need to get a list of all unique values in that column. I know there has to be an easier way to do this, but I can't find my answer anywhere. Here is what I'm doing so far:
$result = mysql_query("SELECT DISTINCT column FROM modx_scripture_table WHERE column!=''", $con);
$filter_all = array();
while($row = mysql_fetch_array($result))
{
$filter_all[] = $row;
}
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
$filter_flat = array_flatten($filter_all);
function array_explode($array) {
$result = array();
foreach ($array as $key => $value) {
$result[$key] = explode(';',$value);
}
return $result;
}
$filter_sploded = array_explode($filter_flat);
$filter_full = array_flatten($filter_sploded);
$filter_final = array_unique($filter_full);
print_r($filter_final);
Everything seems to be working except the array_unique. I'm still getting duplicate strings in $filter_final. What am I doing wrong?
After exploding the string use array_unique() for fnding unique values in an array.
Example:
$arr=array('1','2','3','4','5','3','1');
print_r(array_unique($arr));
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)