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`
Related
Looping through an Array of stdClass Objects, I'd like to add a new property to the Object.
Of all the ways I've tried and researched, none end up adding the new property.
Array
(
[0] => stdClass Object
(
[id] => 12345678
[profile] => stdClass Object
(
[type] => superAdmin
)
)
[1] => stdClass Object
(
[id] => 89101112
[profile] => stdClass Object
(
[type] => admin
)
)
)
I have a function that takes in the above array, and then should iterate through it, if certain criteria met, add a new property to the object, and return the array.
public function addToProfile($usernameArr) {
$users = $usernameArr;
foreach ($users as $key => $user) {
if (in_array("admin", $user->profile->type)) {
$users[$key]->profile->newProperty = "newItem";
}
}
return $users;
}
I've also tried the json_decode(json_encode($users), true) way which did not end up with the result I'm looking for.
You can do it via transformation $user object to the array and back to object:
foreach ($users as $key=>&$user) {
if (in_array("admin", $user->profile->type)) {
// represents current $user->profile object as an array
$tmp = json_decode(json_encode($user->profile),true);
// add a new index
$tmp['newproperty'] = "$key newItem";
// transform back to an object
$user->profile = (object)($tmp);
}
}
Demo
You can put it into the function like:
function addNewProp($data, $prop_name, $prop_val){
foreach ($data as $key=>$user) {
if (in_array("admin", $user->profile->type)) {
$tmp = json_decode(json_encode($user->profile),true);
$tmp[$prop_name] = $prop_val;
$user->profile = (object)($tmp);
}
}
return $data;
}
Demo
Your input value of type has string datatype. Instead of
if (in_array("admin", $user->profile->type)) {
you should use
if ($user->profile->type === "admin") {
Generally, I try and avoid doing things like (object)array(...) and json_decode(json_encode()) in PHP as it is not immediately clear to the reader why your doing this round about stuff, so I will provide an alternative answer.
function addNewProp(array $users, $propName, $propVal)
{
for ($i = 0; $i < count($users); $i++) {
// You may need to do extra checking here if profile and type are not required.
if (isset($users[$i]->profile->type->admin)) {
$users[$i]->profile->$propName = $propVal;
}
}
return $users;
}
Hi i am working on some array operations with loop.
I want to compare array key value with the given name.
But i am unable to get exact output.
This is my array :
Array
(
[0] => Array
(
[label] =>
[value] =>
)
[1] => Array
(
[label] => 3M
[value] => 76
)
[2] => Array
(
[label] => Test
[value] => 4
)
[3] => Array
(
[label] => Test1
[value] => 5
)
[4] => Array
(
[label] => Test2
[value] => 6
)
)
This is my varriable which i need to compare : $test_name = "Test2";
Below Code which i have tried :
$details // getting array in this varriable
if($details['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
But every time its returns NotFound.
Not getting what exactly issue.
#Manthan Dave try with array_column and in_array() like below:
<?php
if(in_array($test_name, array_column($details, "label"))){
return $test_name;
}
else
{
return "NotFound";
}
$details is a multidimensional array, but you are trying to access it like a simple array.
You need too loop through it:
foreach ($details as $item) {
if($item['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
}
I hope your array can never contain a label NotFound... :)
You have array inside array try with below,
if($details[4]['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
Although foreach loop should work but if not try as,
for($i=0; $i<count($details); $i++){
if($details[$i]['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
}
Traverse your array like this,
array_walk($array, function($v) use($test_name){echo $v['label'] == $test_name ? $test_name : "NotFound";});
Just use in_array and array_column without use of foreach loop as
if (in_array($test_name,array_column($details, 'label')))
{
return $test_name;
}
else
{
return "NotFound";
}
You need to check only the if condition like below because else meet at first time it will return the "notfound" then it will not execute.
$result = 'NotFound';
foreach ($details as $item) {
if($item['label'] == $test_name)
{
$result = $test_name;
}
}
return $result;
or
$result = 'NotFound';
if (in_array($test_name,array_column($details, 'label')))
{
$result = $test_name;
}
return $result;
I have an array, I applied in_array function to find a specific number in that array, but it's showing no result, the data is inside the array but no response..:(
Array:
Array
(
[0] => SimpleXMLElement Object
(
[0] => 572140
)
[1] => SimpleXMLElement Object
(
[0] => 533167
)
[2] => SimpleXMLElement Object
(
[0] => 572070
)
[3] => SimpleXMLElement Object
(
[0] => 572383
)
[4] => SimpleXMLElement Object
(
[0] => 285078
)
[5] => SimpleXMLElement Object
(
[0] => 430634
)
}
CODE I AM USING:
if(in_array('285078',$arr))
{
echo 'yes';
}
else
{
echo "No";
}
This is the array I am creating from the xml file..
$arr = array();
foreach($xmlInjury as $data)
{
array_push($arr,$data->player_id);
}
It's only showing 'NO'.. please help me on this...
You need to cast them all first, then search. Like this:
$new_arr = array_map(function($piece){
return (string) $piece;
}, $arr);
// then use in array
if(in_array('285078', $new_arr)) {
echo 'exists';
} else {
echo 'does not exists';
}
First, your array is not array of strings, it's array of objects.
If you can't change the structure of array try this:
foreach ($your_array as $item) {
if (strval($item) == '25478') {
echo 'found!';
break;
}
}
If you can change your array, add items to it like this:
$your_array[] = strval($appended_value);
After that you can use in_array.
in_array is not recursive, it searches only on first level.
and first level member of you array are SimpleXMLElement Objects, not an numbers.
Try with typecasting your array :-
$array = (array) $yourarray;
if(in_array('285078',$arr))
{
echo 'yes';
}
else
{
echo "No";
}
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
}
I'm trying to read recursively into an array until I'm getting a string. Then I try to explode it and return the newly created array. However, for some reason it does not assign the array:
function go_in($arr) { // $arr is a multi-dimensional array
if (is_array($arr))
foreach($arr as & $a)
$a = go_in($a);
else
return explode("\n", $arr);
}
EDIT:
Here's the array definition as printed by print_r:
Array
(
[products] => Array
(
[name] => Arduino Nano Version 3.0 mit ATMEGA328P
[id] => 10005
)
[listings] => Array
(
[category] =>
[title] => This is the first line
This is the second line
[subtitle] => This is the first subtitle
This is the second subtitle
[price] => 24.95
[quantity] =>
[stock] =>
[shipping_method] => Slow and cheap
[condition] => New
[defects] =>
)
[table_count] => 2
[tables] => Array
(
[0] => products
[1] => listings
)
)
I'd use this:
array_walk_recursive($array,function(&$value,$key){
$value = explode("\n",$value);
});
However, this fixes your function:
function &go_in(&$arr) { // $arr is a multi-dimensional array
if (is_array($arr)){
foreach($arr as & $a) $a = go_in($a);
} else {
$arr = explode("\n", $arr);
}
return $arr;
}
When writing nested conditions/loops - always add braces for better readability and to prevent bugs.. Also you should return the go_in function, because it is recursive, it needs to be passed to the calling function instance.
function go_in($arr) { // $arr is a multi-dimensional array
if (is_array($arr))
{
foreach($arr as &$a)
{
return go_in($a);
}
}
else
{
return ($arr);
}
}
The original array was not returned in the function:
function go_in($arr) {
if (is_array($arr))
foreach($arr as &$a)
$a = go_in($a);
else
if (strpos($arr, "\n") !== false)
return explode("\n", $arr);
return $arr;
}
EDIT:
Now, it only really edits the strings that contain a linebreak. Before it would edit every string which meant that every string was returned as an array.