Anonymous PHP function with in_array not working - php

I have this simple array $tree in PHP that I need to filter based on an array of tags matching those in the array.
Array
(
[0] => stdClass Object
(
[name] => Introduction
[id] => 798162f0-d779-46b6-96cb-ede246bf4f3f
[tags] => Array
(
[0] => client corp
[1] => version 2
)
)
[1] => stdClass Object
(
[name] => Chapter one
[id] => 761e1909-34b3-4733-aab6-ebef26d3fcb9
[tags] => Array
(
[0] => pro feature
)
)
)
I tried using an anonymous function like so:
$selectedTree = array_filter($tree, function($array) use ($selectedTags){
return in_array($array->tags, $selectedTags, true);
});
$selectedTags:
Array
(
[0] => client corp
)
The above is returning empty when I'd expect item 1 to be returned. No error thrown. What am I missing?

In case of in_array($neddle, $haystack). the $neddle must need to be a String, but you're giving an array that is why its not behaving properly.
But if you like to pass array as value of $selectedTags then you might try something like below:
$selectedTree = array_filter($tree, function($array) use ($selectedTags){
return count(array_intersect($array->tags, $selectedTags)) > 0;
});
Ref: array_intersect

If I am reading the question correctly, you need to look at each object in $tree array and see if the tags property contains any of the the elements in $selectedTags
Here is a procedural way to do it.
$filtered = array();
foreach ($tree as $key => $obj) {
$commonElements = array_intersect($selectedTags, $obj->tags);
if (count($commonElements) > 0) {
$filtered[$key] = $obj;
}
}
I was going to also post the functional way of doing this but, see thecodeparadox's answer for that implementation.

Related

Problems changing values in an array/object nested combination array

I don't know what to do to get this done what would like to do. I tried multiple approaches, e.g. I used array_map, array_walk, nested foreach loops with get_object_vars and I worked with json_decode/encode and so on. I always come a little bit further but never reach my goal and I would like to get some guidance from you
Basically when you see the array below, how would you proceed when you want to change some value in the path array for multiple values in the array itself?
My questions:
1) Is it right that I must convert both nested objects to an array first or is this not nesessary to do this? I mean I always get some type conversion error which tells me that I either have everything as an object or array. Is this right?
2) If this mistery is solved, which php array function is the appropriate one to change values in an array(/object)? As I have written above, I tried so many and I don't see the trees in the woods anymore. Which one do you suggest to me to use in a foreach loop?
Array
(
[0] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Bob
[1] => pictures
[2] => food
)
)
)
[1] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Alice
[1] => pictures
[2] => vacations
[3] => rome
)
)
)
)
I would suggest that,
you create an array with keys as new path and value as old path (
path to be replaced).
Loop you path array and check if it is available in above defined array.
If available replace it with key of above defined array.
For example
// array defined as point 1
$change_path_array= array('pics'=>'pictures','meal'=>'food');
// $array is your array.
foreach ($array as $value) {
// loop you path array
for($i=0;$i<count($value->doc->path);$i++){
// check if the value is in defined array
if(in_array($value->doc->path[$i],$change_path_array)){
// get the key and replace it.
$value->doc->path[$i] = array_search($value->doc->path[$i], $change_path_array);
}
}
}
Out Put: picture is replaced with pics and food with meal
Array
(
[0] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Bob
[1] => pics
[2] => meal
)
)
)
[1] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Alice
[1] => pics
[2] => vacations
[3] => rome
)
)
)
)
You can modify the code to check casesensitive.
Example of changing all pictures to photos:
$doc1 = new \stdClass;
$doc1->doc = new \stdClass;
$doc1->doc->path = array('Bob', 'pictures', 'food');
$doc2 = new \stdClass;
$doc2->doc = new \stdClass;
$doc2->doc->path = array('Alice', 'pictures', 'vacations', 'rome');
$documents = array($doc1, $doc2);
/* change all 'pictures' to 'photos' */
foreach ($documents as &$doc) {
foreach ($doc->doc->path as &$element) {
if ($element == 'pictures') {
$element = 'photos';
}
unset($element);
}
unset($doc);
}
print_r($documents);
You can do it like this:
for($i = 0; $i < count($arr); $i++){
$path_array = $arr[$i]->doc->path;
// do your modifications for [i]th path element
// in your case replace all 'Bob's with 'Joe's
$path_array = array_map(function($paths){
if($paths == 'Bob') return 'Joe';
return $paths;
}, $paths_array);
$arr[$i]->doc->path = $path_array;
}

How to get an array element

I have an array $data, here's print_r($data) values:
[ProductProperties] => Array
(
[ProductProperty] => Array
(
[0] => Array
(
[Additionaldescription] => microphone, blabla
)
[1] => Array
(
[interface] => USB 2.0
)
[2] => Array
(
[Model] => C310 HD
)
[3] => Array
(
[Manufacturer] => Logitech
)
[4] => Array
(
[Color] => Black
)
)
)
If i want to display "interface" value, i have to do like that:
echo $data['ProductProperties']['ProductProperty'][0]['interface'];
But in my case these numbers are always changing, so this is a no go for using a method above. Can i choose directly "interface" value without mentioning a number index, e.g.:
echo $data['ProductProperties']['ProductProperty']['interface'];
Thanks in advance. (using php 5.5)
No, you can't in the way you wrote. You must loop through the whole $data['ProductProperties']['ProductProperty'] array, and check for the existance of interface key in the nested array.
No, you can't unless you write a function for it manually. You will have to iterate through the array you want to search in and use the array_key_exists function to check for existence of that key.
A little snippet that will help you along the way:
foreach($data['ProductProperties']['ProductProperty'] as $array)
if(array_key_exists("KEY_TO_SEARCH_FOR", $array))
return $array;
no, but you can write your function to get out the interface
$interface = getInterFace($data['ProductProperties']['ProductProperty']);
function getInterFace($array) {
foreach ($array as $element) {
if (isset($element['interface'])) {
return $element['interface'];
}
}
return false;
}

I want to add sub arrays to one single array keep id and value in php

My input array :
Array
(
[0] => Array
(
[id] => 1
[status_name] => Released
)
[1] => Array
(
[id] => 2
[status_name] => Under Construction
)
)
I want the output result :
Array (
[1] => Released
[2] => Under Construction
)
USe sub array id as output array key value and status_name as value array.
This is built into php as array_column. You would have:
$status_names = array_column($data, 'status_name', 'id');
print_r($status_name);
Bonus points on question as I had no idea this existed until looking for an answer for you.
Try the following:
function reOrderArray($input_array)
{
$result = array();
foreach ($input_array as $sub_array)
{
$result[$sub_array['id']] = $sub_array['status_name'];
}
return $result;
}
There might be a built-in php function to do this, array functions in php are quite powerful. I am, however, woefully unaware of one.

Organize multidimensional array using Recursion

I have an array that I've build dynamically. It has many nested arrays because of the way it's built, but the depth is useless to me, so I organize it right afterwards. It could look like this:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[index] => -1
[cost] => 0.189956571618
)
)
)
)
[1] => Array
(
[index] => -1
[cost] => 2.18650011647
)
)
I want to almost-flatten this array (i.e. access its data using $array[$i]['cost'] on all entries, regardless if they were nested deep before I processed them). So far I've been using SPL recursion, with something along these lines:
function flatten($array) {
$return = array();
$it = new RecursiveIteratorIterator(new ParentIterator(new RecursiveArrayIterator($array)), RecursiveIteratorIterator::SELF_FIRST);
foreach($it as $value) {
if(isset($value['cost'])) {
$return[] = $value;
}
}
return $return;
}
It works for the most part, but some of the values in the original array, which do have a 'cost' index in them, fail to be added to the new array because they are passed as nested arrays themselves, like so:
Array
(
[0] => Array
(
[index] => -1
[cost] => 0.189956571618
)
[1] => Array
(
[index] => -1
[cost] => 2.18650011647
)
)
...instead of just (which most of the time I get):
Array
(
[index] => -1
[cost] => 0.189956571618
)
I thought the whole point of using a RecursiveIterator was to go deep within the array and fetch the entries which don't have arrays within them (i.e. the 'values' I want). Am I using the wrong tools for this job? If so, what would be more appropriate to loop through an array for which I don't know the depth? If SPL is the way to go, what am I doing wrong?
Thanks in advance.
you could use array_walk_recursive
EDIT
function flatten($array) {
$return = array();
array_walk_recursive($array, function($value, $key) use (&$return) {
if(isset($value['cost']) $return[] = $value;
});
return $return;
}
on the SPL part EDIT long discussion in the chatroom, check OP's answer

How to access stdclass object after a specific key value pair?

I have a stdclass object as shown below:
stdClass Object
(
[text] => Parent
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Laurence W. Lane Jr.
[url] => http://www.freebase.com/view/m/0c02911
)
)
)
I iterate over multiple such objects, some of which have
stdClass Object
(
[text] => Named after
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Stanford
[url] => SomeURL
)
)
)
I was wondering how I would access the "values" object if it comes after a "text" that has "Parent" as its value?
there are serveral ways to turn it to array:
First Solution:
$value = get_object_vars($object);
Second Solution:
$value = (array) $object;
Third Solution
$value = json_decode(json_encode($object), true);
to get value of converted array
echo $value['values']['0']['id'];
The alternate way to access objects var without convert the object, try
$object->values->{'0'}->id
Expanding (or rather minimalizing) upon answer by Somwang Souksavatd, I like accessing Object values like this:
echo get_object_vars($object)['values']['0']['id'];
I had the same issue, still not so sure why but I was able to get it working using this workaround:
$k2 ="1";
$elements = json_decode('{"id":"1","name":"User1"}');
//$elements['id'] == $k2; //****Not Working
$tmp = (object)$elements;
$tmp = $tmp ->id; //****Working
//$tmp =$elements['id'] ; //****Not Working
return $tmp == $k2;
I have to say that sometimes accessing the element as array works and some times not,(On PHP7 it worked for me but on PHP5.6 it didn't).
$elements can be Array to but I chose to demonstrate with json string.
I hope this helps somehow !!!
$Obj=stdClass Object
(
[text] => Named after
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Stanford
[url] => SomeURL
)
)
)
$Values= $result->values;
$Item = $Values[0];
$id=$Item->id;
$text = $Item->text;
$url=$Item->url;
I'm doing the same thing and all I did was this;
<?php
$stdObject = json_decode($stdClassObject);
print $stdObject->values[0]->id;
this can help you accessing subarrays in php using codeigniter framework
foreach ($cassule['tarefa'][0] as $tarefa => $novo_puto_ultimos_30_dias) {
echo $novo_puto_ultimos_30_dias;
What you are looking for is the Object['values'][0]: 'values' is the keymap just like 'text', and [0] is the index inside that array you wish to access. so if you would like to get the id deep in the nest, you'd have to do something like
Object['values'][0]['id']
or
Object['values'][0]->id
which should give you /m/0c02911. But I have no idea how you are doing your loop, so you will have to adjust it to your needs and place proper variables where they need to go in that code in your loop. Not exactly sure which language you are working with.

Categories