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";
}
Related
I have below type of array, now I want to get count of it's subarray
For example I want to get count key 7 & 8. How to do it ? Any solution for that ? I tried but but no success :(
Array
(
[0] => stdClass Object
(
[id] => 4
[Blogdata] => stdClass Object
(
[7] => Array
(
[0] => stdClass Object
(
[blog_id] => 105
)
)
[8] => Array
(
[0] => stdClass Object
(
[blog_id] => 101
)
)
)
)
)
$date_count = array();
foreach($FeaturedBlogs as $Key=>$date) {
foreach($date as $d) {
$key = array_keys($d); // get our date
// echo $key;echo "<br>";
print_r($d);
$date_count[$key[0]]++;
}
}
Try this....
//Count Sub Array
$final_array = [];
$x = 0;
function countSubArray($data)
{
global $final_array;
global $x;
foreach($data as $key)
{
if(is_array($key))
{
$final_array[$x][0] = "1";
$final_array[$x][1] = json_encode($key);
$final_array[$x][2] = count((array)$key);
$x++;
countSubArray($key);
}
if(is_object($key))
{
$final_array[$x][0] = "2";
$final_array[$x][1] = json_encode($key);
$final_array[$x][2] = count((array)$key);
$x++;
countSubArray($key);
}
}
}
// Call Function...
countSubArray($arr); // what array you count..
// Display Sub Array Count...
$t_count = 0;
foreach($final_array as $d)
{
if($d[0] == 1)
{
echo "Array Count :".$d[2]." Array : ".$d[1]."<br>";
$t_count++;
}
}
echo "Total Array Count :".$t_count;
output of this example is...
Array
(
[0] => stdClass Object
(
[id] => 4
[Blogdata] => stdClass Object
(
[7] => Array
(
[0] => stdClass Object
(
[blog_id] => 135
)
)
[8] => Array
(
[0] => stdClass Object
(
[blog_id] => 101
)
)
)
)
)
Array Count :1 Array : [{"blog_id":135}]
Array Count :1 Array : [{"blog_id":101}]
Total Array Count :2
Updated Answer
This is going to use a function as it's own callback function. The function will loop through an object or an array and test each element to see if it is another object or array.
If it did find a new object or array, then the function calls itself again to perform the same operations on the element, effectively traversing through your entire array.
When it has found the bottom of each element it will return the value of the counter which was keeping track of how many arrays it came across.
Like so:
function arrayCounter($data){
//At this point we have an array or an object.
//Lets loop across the elements and see if we have any more nested arrays or objects.
foreach($data as $key){
$count = 0;
//Test each element to see if it's an object or an array.
if(is_array($key) || is_object($key)){
//If it is we are going to send the element through another instance of the function.
$count += arrayCounter($key);
}
//If the element is an array we are going to increment the counter.
if(is_array($key)){
$count++;
}
}
return $count;
}
$count = arrayCounter($data);
echo 'Count: ' . $count; //Using your data this will return "2".
Hope it helps!
The Array contains some non-empty arrays . i need to fetch respective non-empty array and print the data . eg: array 2 has variable as importTroubles->troubleMessage how can i print that?
Array
(
[0] => stdClass Object
(
)
[1] => stdClass Object
(
)
[2] => stdClass Object
(
[return] => stdClass Object
(
[failureMessage] =>
[importTroubles] => stdClass Object
(
[kind] => ParseError
[rowNumber] => 1
[troubleMessage] => Field "number1" has invalid value: "+16046799329". Invalid phone number //need to print this..
)
[keyFields] => number1
[uploadDuplicatesCount] => 0
[uploadErrorsCount] => 1
[warningsCount] => stdClass Object
(
)
[callNowQueued] => 0
[crmRecordsInserted] => 0
[crmRecordsUpdated] => 2
[listName] => new camp from CRM1-TargetList-CRM
[listRecordsDeleted] => 0
[listRecordsInserted] => 2
)
)
[3] => stdClass Object
(
)
[4] => stdClass Object
(
)
)
im trying with this method :
foreach($result as $object) {
foreach ($object as $items) {
if($items !== '')
{
foreach ($items as $item) {
echo "ERROR".$item->troubleMessage;
}
}
}
}
Thanks for your efforts
Make use of php function empty()
Change your if condition as in below code :
foreach($result as $object) {
foreach ($object as $items) {
if( !empty($items) )
{
foreach ($items as $item) {
if( isset($item->troubleMessage) )
{
echo "ERROR".$item->troubleMessage;
}
}
}
}
}
Now it will echo only if $items has values.
You don't have to iterate each object if you're only looking for a single specific item nested within it. You can just refer to that item directly.
foreach ($your_array as $object) {
if (isset($object->return->importTroubles->troubleMessage)) {
echo $object->return->importTroubles->troubleMessage;
}
}
If you check if that specific nested object variable is set, it will ignore any empty objects.
change your if($items !== '') to if(!empty($items)) or if($items) or if($items[0]) hope it helps
You could use Collection
use Illuminate\Support\Collection;
$collection = new Collection($result);
$items = $collection->filter(function($object) {
return isset($object->return->importTroubles->troubleMessage);
})->map(function($object) {
return $object->return->importTroubles->troubleMessage;
});
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 want would like to get the parent node of the array below, but I don't find a way to easily do this.
Normally for getting the id, I would do this in PHP:
echo $output['posts']['11']['id'];
But how can I get to the parent node "11" when I get the value of "id" passed from a $_GET/$_POST/$_REQUEST? (ie. $output['posts']['11'][$_GET[id]])
Array
(
[posts] => Array
(
[11] => Array
(
[id] => 482
[time] => 2011-10-03 11:26:36
[subject] => Test
[body] =>
[page] => Array
(
[id] => 472
[title] => News
)
[picture] => Array
(
[0] => link/32/8/482/0/picture_2.jpg
[1] => link/32/8/482/1/picture_2.jpg
[2] => link/32/8/482/2/picture_2.jpg
[3] => link/32/8/482/3/picture_2.jpg
)
)
)
)
$parent = null;
foreach ($array['posts'] as $key => $node) {
if ($node['id'] == $_GET['id']) {
echo "found node at key $key";
$parent = $node;
break;
}
}
if (!$parent) {
echo 'no such id';
}
Or possibly:
$parent = current(array_filter($array['posts'], function ($i) { return $i['id'] == $_GET['id']; }))
How this should work exactly depends on your array structure though. If you have nested arrays you may need a function that does something like the above recursively.
array_keys($output['posts']);
will give you all keys within the posts array, see http://php.net/manual/en/function.array-keys.php
you could try with something like:
foreach ($posts as $post){
foreach( $items as $item){
if ( $item['id'] == [$_GET[id] ){
// here, the $post is referring the parent of current item
}
}
}
I don't think it is possible while an array of array is not a DOM or any tree structure. In an array you can store any reference. but you can not naturally refer to an array containing a reference.
Check rolfs example for array_filter at php manual http://www.php.net/manual/en/function.array-filter.php#100813
So you could do it like this
$filtered = array_filter($output, function ($element) use ($_GET["id"]) { return ($element["id"] == $_GET["id"]); } );
$parent = array_pop($filtered);
I have a recursion function that parses an object/array with a global variable. If I comment out the global variable I get nothing but if I leave it in it keeps adding to the array other values that should be in it own result set. Do I need to change something here?
UPDATE #2:
How can I get the return I want, I thought I was pushing all unique values to the array?
function getResp($objectPassed) {
foreach($objectPassed as $element) {
if(is_object($element)) {
// recursive call
$in_arr = getResp($element);
}elseif(is_array($element)) {
$in_arr = getResp($element);
} else {
// XML is being passed, need to strip it
$element = strip_tags($element);
// Trim whitespace
$element = trim($element);
// Push to array
if($element != '') {
if (!preg_match("/^[0-9]$/", $element)) {
if (!in_array($element,$in_arr)) {
$in_arr[] = $element;
}
}
}
}
}
return $in_arr;
}
INPUT:
stdClass Object
(
[done] => 1
[queryLocator] =>
[records] => Array
(
[0] => stdClass Object
(
[type] => typeName
[Id] => Array
(
[0] => a0E50000002jxhmEAA
[1] => a0E50000002jxhmEAA
)
)
[1] => stdClass Object
(
[type] => typeName
[Id] => Array
(
[0] => a0E50000002jxYkEAI
[1] => a0E50000002jxYkEAI
)
)
)
[size] => 2
)
RETURN:
Array
(
[0] => a0E50000002jxYkEAI
)
WANTED RETURN:
Array
(
[0] => a0E50000002jxYkEAI
[1] => a0E50000002jxhmEAA
)
Is a global variable necessary? Otherwise you could simplify it this way:
function getResp($objectPassed, &$in_arr = array()) { // <-- note the reference '&'
foreach($objectPassed as $element) {
if(is_object($element) || is_array($element)) { // <-- else if statement simplified
getResp($element,$in_arr);
} else {
// XML is being passed, need to strip it
$element = strip_tags($element);
// Trim whitespace
$element = trim($element);
// Push to array
if($element != '' && // <-- everything in one test
!preg_match("/^[0-9]$/", $element) &&
!in_array($element,$in_arr))
{
$in_arr[] = $element;
}
}
}
return $in_arr;
}
Then you do:
$result = getResp($data);
If a recursive function has to access the same resource over and over again (in this case the initial array), I would always pass this as a reference.
I don't know if is measurable but I would guess that this is much more efficient than copying values.