PHP in_array() unexpected result - php

This is the $feed_content array
Array
(
[0] => Array
(
[id] => 1
[link] => http://www.dust-off.com/10-tips-on-how-to-love-your-portable-screens-keeping-them-healthy
)
[1] => Array
(
[id] => 2
[link] => http://www.dust-off.com/are-you-the-resident-germaphobe-in-your-office
)
)
----Another array----------
This is the $arrFeeds array
Array
(
[0] => Array
(
[title] => 10 Tips on How to Love Your Portable Screens (Keeping them Healthy)
[link] => http://www.dust-off.com/10-tips-on-how-to-love-your-portable-screens-keeping-them-healthy
)
[1] => Array
(
[title] => Are You the Resident Germaphobe in Your Office?
[link] => http://www.dust-off.com/are-you-the-resident-germaphobe-in-your-office
)
)
Here's my code:
foreach( $arrFeeds as $key2 => $value2 )
{
$feed_content = $feed->get_feed_content( $value['id'] );
if( !in_array( $value2['link'], $feed_content ) )
{
echo "not match!";
}
}
Question:
Why is it that the code always enters into the if statement even if $feed_content link value has the value of the $arrFeeds link?
My expected result should be that my code would tell me if the $feed_content link value is not in the $arrFeeds.
By the way, the $feed_content code returns an array that I specified above.
What should be the problem with this one. Thanks in advance! :)

that's because the elements of your array called $feed_content are associative arrays also (with the id and link keys)
you are checking if the link (a string) is equal to any of the elements in the array (all of them arrays)
Edit:
To achieve what you want you can use a "hack". Instead of in_array you can use something like:
$search_key = array_search(array('id'=>true,'link'=>$value2['link']), $feed_content);//use true for the id, as the comparison won't be strict
if (false !== $search_key)//stict comparison to be sure that key 0 is taken into account
{
echo 'match here';
}
this thing relies on the fact that you can use an array for the search needle for the array_search function and that the comparison won't be strict, so true will match any number (except 0, but I guess that you don't use 0 as an id)
this way the only field that will really matter is the one for the link
after that you need to use a strict comparison this time to be sure that if the found key is 0 you will use it

in_array doesn't search recursively. It sees $feed_content as
Array
(
[0] => Array
[1] => Array
)
Now you could extend your if clause to foreach through $feed_content:
$found = false;
foreach($feed_content as $feedArr)
{
if(in_array($value2['link'], $feedArr))
{
$found = true;
}
}
if(!$found) echo "not match!";

if( !in_array( $value2['link'], $feed_content ) )
if( !in_array( $value2['link'], array_values($feed_content)) )

Related

PHP recursive function returning null array

I have a huge array in which keys are also not constant in most of the cases, but there are 3 keys that always constant (#name,#default_value,#value) and #default_value and #value is different i want to get these kind of sub arrays in 1 simple array , for this purpose i am using recursion in whole array and checking out if these 3 keys are present there i can print these values inside recursion easily but I am not able to get those values in return. So that i can precess them further.
$form=array();
$form['field_one']['#name']="field_one";
$form['field_one']['#default_value']="old";
$form['field_one']['#value']="new";
$form['field_two']['#name']="field_two";
$form['field_two']['#default_value']="old";
$form['field_two']['#value']="new";
$form['field_three']['#name']="field_three";
$form['field_three']['#default_value']="old";
$form['field_three']['#value']="old";
$form['thiscouldbeanotherarray']['idk']['field_four']['#name']="field_four";
$form['thiscouldbeanotherarray']['idk']['field_four']['#default_value']="old";
$form['thiscouldbeanotherarray']['idk']['field_four']['#value']="new";
$arr_get = get_updatedvalues($form,array());
var_dump($arr_get);
function get_updatedvalues($form,$fields) {
if (!is_array($form)) {
return;
}
foreach($form as $k => $value) {
if(str_replace('#','',$k) =='default_value' && ($form['#default_value'] != $form['#value'] ) ){
$fields['field'][$form['#name']] = array("name" => $form['#name'],"old_value" =>$form['#default_value'],"new_value" =>$form['#value']);
var_dump($fields);
}
get_updatedvalues($value,$fields);
}
return $fields;
}
If you run this code it will give you $arr_get > array (size=0), there i need all three values
If I understand correctly, you need to pass fields as a reference in order to change it:
function get_updatedvalues($form, &$fields) {
To do that, however, you'll need to change your initial call so that you have a variable to pass as the reference:
$array = [];
$arr_get = get_updatedvalues($form,$array);
Running this I get:
Array
(
[field] => Array
(
[field_one] => Array
(
[name] => field_one
[old_value] => old
[new_value] => new
)
[field_two] => Array
(
[name] => field_two
[old_value] => old
[new_value] => new
)
[field_four] => Array
(
[name] => field_four
[old_value] => old
[new_value] => new
)
)
)

Searching all values from a specific Index in multidimensional, associative Array in php by Index, not by value

with some help of this forum i found a way to get an array that perfectly fits my task. I ran into a follow-up problem tho:
I got the following example-array
Array (
[A] => Array (
[D] => Array (
[A] => Array (
[M] => Array (
[result] => ADAM )
[N] => Array (
[result] => ADAN )
)
)
)
[H] => Array (
[E] => Array (
[N] => Array (
[R] => Array (
[Y] => Array (
[result] => HENRY )
)
[N] => Array (
[E] => Array (
[S] => Array (
[result] => HENNES )
)
)
)
)
)
)
Where the Letters are Indexes and i end up with an result array for each name.
Now i am looking for a way to Search this array with a specific search-string and it should be possible from the 3rd Char on. So if i Search for 'ADA' i want to get the value from all following result-arrays which would be "ADAM" and "ADAN" as both follow on Array['A']['D']['A'].
I didnt have any trouble starting to search at the right Index but i cant figure out a way to access all 'result'-arrays. Only found ways to search for the final Value (ADAM, ADAN) but as statet im looking for all final values possible from my searchpoint.
So basically i want to get all Values from the result arrays following the last Char from my Search-String as Index of my Array. Hopefully that explanation points out what im looking for.
Thanks in Advance!
In short:
//my Input
$searchstring = 'ADA';
//Output i want
"ADAM", "ADAN";
//Input
$searchstring = 'ADAM';
//Output
"ADAM"
EDIT: I edited this question with my approach so far as a comment pointed out i should do this (thanks for that! ) so i tried to go this way:
When i had my Example-Array i tried to only select the necessary part of the structure:
$searchquery = 'HEN';
//Searchquery as Array
$check = str_split($searchquery);
//second isntance of the original array which is named $result
$finalsearch = $result;
foreach($check as $key) {
$finalsearch = $finalsearch[$key];
}
//check with output if i selected the right area
print_r($finalsearch);
Output i got from this:
Array ( [R] => Array ( [Y] => Array ( [result] => HENRY ) ) [N] => Array ( [E] => Array ( [S] => Array ( [result] => HENNES ) ) ) )
So i am in the right are of the structure.
then i tried to find ways to search for all Instances of the index 'result'.
i found the following functions and approaches that all enabled me to search for a specific value but not the indexes.
$newArray = array_values($finalsearch);
array-search($searchquery, $finalsearch);
That was the Point where i started turning in circles
First part is to find the start point for the list, this is just a case of looping over each character in the search string and moving onto that value in the array.
Once you have found the start point, you can use array_walk_recursive() which will only visit the leaf nodes - so this will only be the names (in this case), so create a list of all these nodes and return them...
function getEntry ( array $result, string $search ) {
for($i = 0; isset($search[$i]); $i++){
$result = $result[$search[$i]];
}
$output = [];
array_walk_recursive($result, function ( $data ) use (&$output) {
$output[] = $data;
});
return $output;
}
$searchstring = 'ADA';
print_r(getEntry($result, $searchstring));
which should give...
Array
(
[0] => ADAM
[1] => ADAN
)
This script first iterates over the keys containing the chars of $searchstring and if it has found it and no errors were thrown, it walks the array recursively to find all result keys to add it to the $result array. After that it implodes the $result array and echos it.
$searchstring = 'HE';
for( $i = 0; $i < strlen( $searchstring ); $i++ ) {
$sub = #( isset( $sub ) ? $sub[$searchstring[$i]] : $array[$searchstring[$i]] )
or die( 'no results found' );
}
array_walk_recursive( $sub, function( $value ) use ( &$results ) {
$results[] = $value;
});
echo implode( ', ', $results );

Get Specific Value from Multidimensional Associative JSON

I am trying to get a specific value from a JSON response and am having trouble figuring out how to target it. I can loop through it but I want to only output a single value based on the key as the response is dynamic and not always guaranteed to have the same output.
I have converted the JSON response to an array and here is an example of what I have at this point:
Array (
[0] => Array (
[rel] => advertisements
[href] => https://api.teamsnap.com/v3/advertisements
)
[1] => Array (
[rel] => active_season_team
[href] => https://api.teamsnap.com/v3/teams
)
[2] => Array (
[rel] => assignments
[href] => https://api.teamsnap.com/v3/assignments
)
[3] => Array (
[rel] => availabilities
[href] => https://api.teamsnap.com/v3/availabilities
)
)
I need to be able to echo the "href" value by the key "rel". I have tried:
foreach($links as $key => $value) {
echo $key['advertisements'];
}
But need a way to say $links as $key->rel = $value->http (thats the logic I can come up with)
You can use array_search on the rel column (extracted using array_column) to find the key of a matching value (e.g. advertisements). If it exists, you can then access the value directly:
if(($key = array_search('advertisements', array_column($links, 'rel'))) !== false) {
echo $links[$key]['href'];
}
Output
https://api.teamsnap.com/v3/advertisements
Demo on 3v4l.org
For more flexibility, you could write this as a function:
function get_link($links, $cat) {
if(($key = array_search($cat, array_column($links, 'rel'))) !== false) {
return $links[$key]['href'];
}
else {
return '';
}
}
echo get_link($links, 'active_season_team');
Output:
https://api.teamsnap.com/v3/teams
Demo on 3v4l.org
I didn't understand your requirements but as per syntax, In your case key will be index of array you can get data as below:
foreach($links as $link){
echo $link['rel'].' = '.$link['href'];
}

Create multidimensional array from standard array

Most likely I'm doing this wayyyyyy too complicated. But I'm in the need of converting multiple arrays to multidimensional array key's. So arrays like this:
Array //$original
(
[0] => 500034
[1] => 500035 //these values need to become
//consecutive keys, in order of array
)
Needs to become:
Array
(
[50034][50035] => array()
)
This needs to be done recursively, as it might also require that it becomes deeper:
Array
(
[50034][50036][50126] => array() //notice that the numbers
//aren't necessarily consecutive, though they are
//in the order of the original array
)
My current code:
$new_array = array();
foreach($original as $k => $v){ //$original from first code
if((gettype($v) === 'string' || gettype($v) === 'integer')
&& !array_key_exists($v, $original)){ //check so as to not have illigal offset types
$new_array =& $original[array_search($v, $original)];
echo 'In loop: <br />';
var_dump($new_array);
echo '<br />';
}
}
echo "After loop <br />";
var_dump($new_array);
echo "</pre><br />";
Gives me:
In loop:
int(500032)
In loop:
int(500033)
After loop
int(500033)
Using this code $new_array =& $original[array_search($v, $original)]; I expected After loop: $new_array[50034][50035] => array().
What am I doing wrong? Been at this for hours on end now :(
EDIT to answer "why" I'm trying to do this
I'm reconstructing facebook data out of a database. Below is my own personal data that isn't reconstructing properly, which is why I need the above question answered.
[500226] => Array
(
[own_id] =>
[entity] => Work
[name] => Office Products Depot
[500227] => Array
(
[own_id] => 500226
[entity] => Employer
[id] => 635872699779885
)
[id] => 646422765379085
)
[500227] => Array
(
[500228] => Array
(
[own_id] => 500227
[entity] => Position
[id] => 140103209354647
)
[name] => Junior Programmer
)
As you can see, the ID [500227] is a child of [500226], however, because I haven't got the path to the child array, a new array is created. The current parentage only works to the first level.
[own_id] is a key where the value indicates which other key should be its parent. Which is why the first array ([500226]) doesn't have a value for [own_id].
If you want to do something recursively, do it recursively. I hope that's what you meant to do.
public function pivotArray($array, $newArray)
{
$shifted = array_shift($array);
if( $shifted !== null )
{
return $this->pivotArray($array, array($shifted=>$newArray));
}
return $newArray;
}
$array = array(432, 432532, 564364);
$newArray = $this->pivotArray($array, array());
Edit: After the question's edit it doesn't seem to be very relevant. Well, maybe someone will find it useful anyway.

PHP - Check that value doesn't appear twice in array

I have a array inside my PHP app that looks like this:
Array
(
[0] => Array
(
[name] => Name1
[language] => 1
)
[1] => Array
(
[name] => Name2
[language] => 1
)
)
How can I check that "language" with value 1 doesnt appear twice, as effectively as possible?
$dupe = 0;
foreach($yourarray as $key => $val) {
if(array_key_exists($seen, $val['language'])) {
// a duplicate exists!
$dupe = 1;
// could do other stuff here too if you want,
// like if you want to know the $key with the dupe
// if all you care about is whether or not any dupes
// exist, you could use a "break;" here to early-exit
// for efficiency. To find all dupes, don't use break.
}
$seen[$val['language']] = 1;
}
// If $dupe still = 0 here, then no duplicates exist.
Tried the PHP function array_unique?
(Read the comments/user contributed notes below, especially the one by regeda at inbox dot ru, who made a recursive function for multi-dimensional arrays)

Categories