Hi I have an object array ($perms_found) as follow:
Array
(
[0] => stdClass Object
(
[permissions_id] => 1
)
[1] => stdClass Object
(
[permissions_id] => 2
)
[2] => stdClass Object
(
[permissions_id] => 3
)
)
I want to use in_array to find any of the permissions_id , I have tried this:
var_dump(in_array(1, $perms_found , true));
But I keep getting :
bool(false)
What I am doing wrong please help?
in_array is looking for 1 in the array, but your array contains objects, not numbers. Use a loop that accesses the object properties:
$found = false;
foreach ($perms_found as $perm) {
if ($perm->permissions_id == 1) {
$found = true;
break;
}
}
Firstly convert to array...
function objectToArray($object) {
if (!is_object($object) && !is_array($object)) {
return $object;
}
if (is_object($object)) {
$object = get_object_vars($object);
}
return array_map('objectToArray', $object);
}
in_array() will check if the element, in this case 1, exists in the given array.
Aparently you have an array like this:
$perms_found = array(
(object)array('permissions_id' => 1),
(object)array('permissions_id' => 2),
(object)array('permissions_id' => 3)
);
So you have an array with 3 elements, none of them is the numeric 1, they are all objects. You cannot use in_array() in this situation.
If you want to check for the permission_id on those objects, you will have to wrote your own routine.
function is_permission_id_in_set($perm_set, $perm_id)
{
foreach ($perm_set as $perm_obj)
if ($perm_obj->permission_id == $perm_id)
return true;
return false;
}
var_dump(is_permission_id_in_set($perms_found, 1));
Your array is collection of objects and you're checking if an integer is in that array. You should first use array_map function.
$mapped_array = array_map($perms_found, function($item) { return $item->permissions_id });
if (in_array($perm_to_find, $mapped_array)) {
// do something
}
Related
i want to get specific key with specific condition with indexing 0,1,2 from multidimensional array using array function only.
using forloop it is getting but i want it using array function for code optimization
my input code like:
Array
(
[0] => Array
(
[device_token] => 1324
[device_type] => 0
)
[1] => Array
(
[device_token] => 2546
[device_type] => 1
)
[2] => Array
(
[device_token] => 13241
[device_type] => 0
)
[3] => Array
(
[device_token] => 12345
[device_type] => 1
)
)
and i want only device_token which have device_type=0 with following format like :
Array
(
[0] => 1324,
[1] => 13241,
)
i am trying following code:
$ios_token = array_map(function($r) {
return $r['device_token'];
}
this give me device token of all.
array_filter should do it for you :
http://php.net/manual/en/function.array-filter.php
$ios_token = array_filter($myArray, function($item) {
return $item['device_type'] == 0;
});
It iterates over each value and if the callback function returns true, the current value of the array is returned.
Then you could pass your variable in an array_map function like you did :
$ios_token = array_map(function($item){
return $item['device_token'];
}, $ios_token);
And if you want to group everything :
$ios_token = array_map(function($item){
return $item['device_token'];
}, array_filter($myArray,
function($item) {
return $item['device_type'] == 0;
}
));
array_map() function gives you more possibilities with arrays.
func_array_map
function myfunction($v)
{
if ($v['device_type']==0)
{
return $v['device_token'];
}
return null;
}
$a=array(...) // your array here
print_r(array_values(array_filter(array_map("myfunction",$a))));
Here you need array_reduce:
$ios_token = array_reduce(
$your_array,
function($t, $v) {
if ($v['device_type'] == 0)
$t[] = $v['device_token'];
return $t;
},
array()
);
Try laconic solution with array_walk:
// assuming $arr is your main array
$result = [];
array_walk($arr, function($v) use(&$result){
if ($v['device_type'] == 0) $result[] = $v['device_token'];
});
var_dump($result);
Following is the array with stdClass Object
Array
(
[0] => stdClass Object
(
[Number] => 5
[Content] => 00666
)
[1] => stdClass Object
(
[Number] => 7
[Content] => 1018456550591052212900797790669502
)
)
What I want to get value of Content corresponding to Number
eg. For Number 5 get value 00666
Thank in advance.
add this function:
function returnContent($myObjectArray, $number)
{
foreach($myObjectArray as $obj){
if ($obj->Number == $number)
return $obj->Content;
}
}
return "number not in array"; //or some other value to denote an error
}
call the function something like this:
echo returnContent($objArray, 5);
or assign it to a variable:
$content = returnContent($objArray, 5);
just be sure to check if the number existed:
if ($content != "number not in array"){ //or whatever value you assigned to denote a failure
//do something
}
You can make a function for this:
function getContent($needle, $haystack) {
foreach($haystack as $v) if($needle==$v->Number) return $v->Content;
return null;
}
To use it use:
$result = getContent(5, $myArray);
if($result===null) die('Value not found.');
// Use result however you want now
$myObjectArray= myObjectArray() // array of objects
foreach($myObjectArray as $val) {
echo $val->Content;
}
It will print `00666` and `1018456550591052212900797790669502`
I'm fetching some JSON from flickrs API. My problem is that the exif data is in different order depending on the camera. So I can't hard-code an array number to get, for instance, the camera model below. Does PHP have any built in methods to search through associative array values and return the matching arrays? In my example below I would like to search for the [label] => Model and get [_content] => NIKON D5100.
Please let me know if you want me to elaborate.
print_r($exif['photo']['exif']);
Result:
Array
(
[0] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => Make
[label] => Make
[raw] => Array
(
[_content] => NIKON CORPORATION
)
)
[1] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => Model
[label] => Model
[raw] => Array
(
[_content] => NIKON D5100
)
)
[2] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => XResolution
[label] => X-Resolution
[raw] => Array
(
[_content] => 240
)
[clean] => Array
(
[_content] => 240 dpi
)
)
$key = array_search('model', array_column($data, 'label'));
In more recent versions of PHP, specifically PHP 5 >= 5.5.0, the function above will work.
To my knowledge there is no such function. There is array_search, but it doesn't quite do what you want.
I think the easiest way would be to write a loop yourself.
function search_exif($exif, $field)
{
foreach ($exif as $data)
{
if ($data['label'] == $field)
return $data['raw']['_content'];
}
}
$camera = search_exif($exif['photo']['exif'], 'model');
$key = array_search('Model', array_map(function($data) {return $data['label'];}, $exif))
The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function. In this case we are returning the label.
The array_search() function search an array for a value and returns the key. (in this case we are searching the returned array from array_map for the label value 'Model')
This would be fairly trivial to implement:
$model = '';
foreach ($exif['photo']['exif'] as $data) {
if ($data['label'] == 'Model') {
$model = $data['raw']['_content'];
break;
}
}
foreach($exif['photo']['exif'] as $row) {
foreach ($row as $k => $v) {
if ($k == "label" AND $v == "Model")
$needle[] = $row["raw"];
}
}
print_r($needle);
The following function, searches in an associative array both for string values and values inside other arrays. For example , given the following array
$array= [ "one" => ["a","b"],
"two" => "c" ];
the following function can find both a,b and c as well
function search_assoc($value, $array){
$result = false;
foreach ( $array as $el){
if (!is_array($el)){
$result = $result||($el==$value);
}
else if (in_array($value,$el))
$result= $result||true;
else $result= $result||false;
}
return $result;
}
$data = [
["name"=>"mostafa","email"=>"mostafa#gmail.com"],
["name"=>"ali","email"=>"ali#gmail.com"],
["name"=>"nader","email"=>"nader#gmail.com"]];
chekFromItem($data,"ali");
function chekFromItem($items,$keyToSearch)
{
$check = false;
foreach($items as $item)
{
foreach($item as $key)
{
if($key == $keyToSearch)
{
$check = true;
}
}
if($check == true)
{break;}
}
return $check;}
As far as I know , PHP does not have in built-in search function for multidimensional array. It has only for indexed and associative array. Therefore you have to write your own search function!!
How do I know if a key in an array is true? If not, then don't use this
[0] => array
(
[id] => 1
[some_key] => something
)
[1] => array
(
[id] => 2
)
[2] => array
(
[id] => 3
[some_key] => something
)
foreach($array as $value){
$id = $value->id;
if($value->some_key === TRUE){
$some_key = $value->some_key; //some may have this key, some may not
}
}
Not sure what is the proper statement to check if this array has that some_key. If I don't have a check, it will output an error message.
Thanks in advance.
Try
isset($array[$some_key])
It will return true if the array $array has an index $some_key, which can be a string or an integer.
Others have mentioned isset(), which mostly works. It will fail if the value under the key is null, however:
$test = array('sampleKey' => null);
isset($test['sampleKey']); // returns false
If this case is important for you to test, there's an explicit array_key_exists() function which handles it correctly:
http://php.net/manual/en/function.array-key-exists.php
You can use the isset() function to see if a variable is set.
foreach($array as $value){
$id = $value->id;
if(isset($value->some_key)){
$some_key = $value->some_key;
}
}
function validate($array)
{
foreach($array as $val) {
if( !array_key_exists('id', $val) ) return false;
if( !array_key_exists('some_key', $val) ) return false;
}
return true;
}
I have this array of objects. However I want to only pull out the object which meets a certain criteria. If you look at the "post_title" key, I want to only pull out the object if it does not contain a comma. Is this possible?
So in my example below, I want to pull out the array in index 2 as that is the only one that has no comma in the "post_title" key.
Array
(
[0] => stdClass Object
(
[ID] => 504
[post_title] => Playroom (Black, Custom 2)
)
[1] => stdClass Object
(
[ID] => 503
[post_title] => Playroom (Black, Custom 1)
)
[2] => stdClass Object
(
[ID] => 252
[post_title] => Play (Black)
)
)
1
Thank you for looking at this.
Yes you can but you will have to code it yourself, like this:
$results = array();
foreach ($source as $obj) {
if (strpos($obj->post_title, ',') === false) {
$results[] = $obj;
}
}
// $results will now have the elements filtered
check array_filter function - http://php.net/manual/en/function.array-filter.php
$myArray = /*snip*/;
function titleDoesNotContainComma($object) {
return strpos($object->post_title, ',') === false;
}
$filteredArray = array_filter($myArray, 'titleDoesNotContainComma');
What have you tried? You could just foreach over the array and build a new array with the relevant results. Alternatively you could use array_filter, something like this:
function hasComma( $object ) {
if( strpos( $object->post_title, ',' ) ) {
return false;
} else {
return true;
}
}
var_dump( array_filter( $array, 'hasComma' ) );