Looping though arrays dealing with null values - php

I have an array myArray
Array ([0] =>(
Number => 02348
Food => Array (
[0] => orange
[1] => apple
[2] => plum )
State => Array (
[0] => california
[1] => texas
[2] => arizona )
Status => good )
[1] =>(
Number => 34
Food => Array (
[0] => grape
[1] => bannana
[2] => tomato )
Status => rotten )
[2] =>(
Number => 007
Food => Array (
[0] => oranges
[1] => apples
[2] => plums )
State => Array (
[0] => ohio
[1] => utah
[2] => vermont )
Status => good )
I am looping though my array and then grabbing the fields i need.
for($index=0; $index < count($myArray); $index++){
$food = array_values(array_filter($myArray[$index]["Food"]));
$states = array_values(array_filter($myArray[$index]["State"]));
For the $states line i get an error of
Notice: Undefined index: State
Warning: array_filter() expects parameter 1 to be array, null given
As you can see in my array State may not always be present, is there a way to get around this. Also there is a large amount of data is being pulled dynamically and it would be difficult to change the structure of the array.
How can i loop though my array ignoring nulls but still keeping the place of State. For example
State => Array (
[0] => ohio
[1] => utah
[2] => vermont )
would still be mapped to the [2], and not shifted to [1].

$states = array_values(array_filter($myArray[$index]["State"]));
Using the above example from your code, the array_filter function expects an array so you will need to check that the variable $myArray[$index]["State"] passed to the function is both set and also an array. This will remove the notices and warnings.
You can test for an array using the is_array() function and test if a variable is set using the isset() function.
In this example, an intermediate variable $states_array is set using data from your array. It checks if the original variable is valid, otherwise, it is set to an empty array. This is then passed into the array_filter function.
$states_array = (isset($myArray[$index]["State"]) && is_array($myArray[$index]["State"])) ? $myArray[$index]["State"] : array() ;
$states = array_values(array_filter($states_array));
You may also be interested to know that PHP 7 provides a null coalesce operator which may be helpful when handling variables that may or may not be set.
See:
http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator

Related

Notice: Undefined index backdrop_path

i want display the backdrop_path of the movie but i get this error
Notice: Undefined index: backdrop_path in /..../public_html/movie.php on line 167
I have added
print_r($tmdbResult);
to see the content of $tmdbResult. I want to display just backdrop_path.
Array
(
[movie_results] => Array
(
[0] => Array
(
[adult] =>
[backdrop_path] => /mbA7SCtJoFTactP1lDHA055qCf.jpg
[genre_ids] => Array
(
[0] => 35
[1] => 28
)
[id] => 261392
[original_language] => en
[original_title] => American Ultra
[overview] => A stoner and his girlfriend's sleepy, small-town existence is disrupted when his past comes back to haunt him in the form of a government operation set to wipe him out.
[release_date] => 2015-08-21
[poster_path] => /6oGHH27nqaLGfpcgYRIZYSJs7AD.jpg
[popularity] => 3.509263
[title] => American Ultra
[video] =>
[vote_average] => 5.6
[vote_count] => 134
)
)
[person_results] => Array
(
)
[tv_results] => Array
(
)
[tv_episode_results] => Array
(
)
[tv_season_results] => Array
(
)
)
The code i use is
ini_set("display_errors",1);
$tmdbResponse = curl_exec($ch);
curl_close($ch);
$tmdbResult = json_decode($tmdbResponse, true );
$backdrop_path = $tmdbResult['movie_results']['backdrop_path'];
$smarty->assign("backdrop_path",$backdrop_path);
print_r($tmdbResult);
The reason is you're getting a numeric index, because the result can contain multiple movies. In this case you're getting just one.
All you need to do is access the array like this #u_mulder said:
$bp = $tmdbResult['movie_results'][0]['backdrop_path'];
The [0] meaning that in case you get multiple results, just need to change that index to access the others. May be you shoulds think of a foreach loop, unless for some reason of yours, you KNOW you'll always get ONE single movie, in that case, hardcode your $bp = $tmdbResult['movie_results'][0]['backdrop_path']; no problem.

How to search a multidimensional array to return multiple keys

I've got a multidimensional array written in php that holds an array of arrays. I've read a lot about how to search this, but it seems most solutions either:
A. require you have unique values for the keys, such as a product id
or
B. are satisfied with returning multiple results in an array
I am looking to search the array given the round number (which is the array number of the highest/first level array), and a player name (which will be the value of either the key player 1 or player 2).
The array looks something like this:
Array (
[0] => Array ( )
[8] => Array (
[1] => Array (
[Match] => 1
[Player1seed] => (Q)
[Player1name] => Mahut
[Player2seed] => (2)
[Player2name] => Goffin
[Matchscore] => 7-6(1), 6-1
[Round] => Finals
)
)
[7] => Array (
[1] => Array (
[Match] => 1
[Player1seed] => (2)
[Player1name] => Goffin
[Player2seed] =>
[Player2name] => Muller
[Matchscore] => 7-6(4), 6-4
[Round] => Semi-Finals
)
[2] => Array
(
[Match] => 2
[Player1seed] => (Q)
[Player1name] => Mahut
[Player2seed] => (WC)
[Player2name] => Haase
[Matchscore] => 5-7, 6-3, 6-4
[Round] => Semi-Finals
)
)
etc.
Essentially, I need to be able to search specifically one subset such as array[7] and be returned the results that contains either player1 or player2 as a name, say Goffin.
But I don't want it to return results from other tournament rounds such as array[8] or array[6] where either player is Goffin.
I can't seem to find this solution anywhere. Am I setting up my array incorrectly? Or expecting database functions from a lesser data set?
Any help would be appreciated.
It's not exactly the way I wanted to solve the problem, but I was able to get the results I wanted by running a loop after identifying the specific round number:
$r = $roundnumber;
foreach( $matchesarray[$r] AS $key=>$data ){
$winnerseed=$data['Player1seed'];
$winnername=$data['Player1name'];
$loserseed=$data['Player2seed'];
$losername=$data['Player2name'];
$matchurl=$data['Matchurl'];
$score=$data['Matchscore'];
if ($p1name == $winnername || $p2name == $losername){
$winner=$p1;
}
else if ($p2name == $winnername || $p1name == $losername){
$winner=$p2;
}
}

Accessing Array Data in Object

I'm trying to access a piece of data in an array of arrays that (I believe) is in an object (this may not be the right term though).
When I do print_r on this: $order_total_modules->process() I get...
Array (
[0] => Array (
[code] => ot_subtotal
[title] => Sub-Total:
[text] => $49.99
[value] => 49.99
[sort_order] => 1
)
[1] => Array (
[code] => ot_total
[title] => Total:
[text] => $0.00
[value] => 0
[sort_order] => 12
)
)
If I run echo $order_total_modules->process()[1][3];, I should get "0", because that is the 3rd element of the 2nd array... right? Yet, I get an error.
Can anyone help with this?
Even though it is the third element counting from 0, the index is not 3 it is an associative array with the index value:
Available in PHP >=5.4.0:
echo $order_total_modules->process()[1]['value'];
Or PHP < 5.4.0:
$result = $order_total_modules->process();
echo $result[1]['value'];
You cannot access an associative array via an integer index(unless the index is an actial integer).
So in this case use :
[1]['code'] to access what woulde be [1][0] with a 'normal' array.
Try putting it in a var first:
$ar = $order_total_modules->process();
echo $ar[1]['value'];
The second level array is an assoc, which means that the key is not numeric, which means that you need to call the name of the key, hence the 'value'.

Handling PHP Array post values and merging - PHP Arrays

I know this won't take much time for experts here. But still please help me out
My Array output is like this
Array ( [0] => 1 [1] => 37 [2] => 1035 ) 1
Array ( [0] => 1 [1] => 37 [2] => 1035 ) mystatusmessage1
Array ( [0] => 4 [1] => 37 [2] => 2925 ) 2
Array ( [0] => 4 [1] => 37 [2] => 2925 ) mystatusmessage2
What I would like to get it is in a single string value like this so that I can insert into database.
1,37,1035,1,mystatusmessage1
4,37,2925,2,mystatusmessage2
How can I achieve that. I'm trying to do with foreach but still I'm not able to do it.
Thanks,
Kimz
use implode function to make string from array for example
if you have array like Array('a','b','c');
implode(',',array('a','b','c') )
will return a,b,c as string
here first argument is your glue by which you want to join string
Here you go.
// Original array
$array = array(0 => 1, 1 => 37, 2 => 1035);
// $_POST array
$_POST = array(1,'mystatusmessage1');
// Jump to the end of array
end($array);
// Merge the post with original array
$newArr = array_merge($array,$_POST);
// Impode
echo implode(",",$newArr);
Repeat with other array.

PHP 5.2 Function needed for GENERIC sorting FOLLOWUP

OK, you guys gave me a great solution for sorting a recordset array last Friday. (PHP 5.2 Function needed for GENERIC sorting of a recordset array)
But now when I implement it, I end up with an extra element in the recordset array. I won't wast space reposting the same info, as the link is above. But the bottom line is that when I sort an array of 5 records, the resulting array has 6 records. The last element in the array is not a record array, but rather just a element containing an integer value of 1. I presume that it is somehow getting the output value of the "strnatcasecmp" function, but I have no idea how it is happening.
Here is the function that you fine folks provided last week:
function getSortCommand($field, $sortfunc) {
return create_function('$var1, $var2', 'return '.$sortfunc.'($var1["'.$field.'"], $var2["' .$field .'"]);');
}
And here is the line I am calling to sort the array:
$trek[] = usort($trek, getSortCommand('name', 'strnatcasecmp'));
This produces the following output, with an extra element tacked on to the end.
Array
(
[0] => Array
(
[name] => Kirk
[shirt] => Gold
[assign] => Bridge
)
[1] => Array
(
[name] => McCoy
[shirt] => Blue
[assign] => Sick Bay
)
[2] => Array
(
[name] => Scotty
[shirt] => Red
[assign] => Engineering
)
[3] => Array
(
[name] => Spock
[shirt] => Blue
[assign] => Bridge
)
[4] => Array
(
[name] => Uhura
[shirt] => Red
[assign] => Bridge
)
[5] => 1
)
Just do
usort($trek, getSortCommand('name', 'strnatcasecmp'));
usort() returns a boolean indicating whether it was executed successfully (it sorts the elements in place):
Return Values
Returns TRUE on success or FALSE on failure.
By doing $trek[] = usort(...), you append the result of the function to the array.

Categories