how to check if values exist inside a multidimensional array - php

i have an array like this:
Array
(
[206] => Array
(
[1] => Array
(
[formatid] => 1
[format] => CD
[formatseourl] => cd
)
)
[556] => Array
(
[] => Array
(
[formatid] =>
[format] =>
[formatseourl] =>
)
)
[413] => Array
(
[3] => Array
(
[formatid] => 3
[format] => CASETE
[formatseourl] => casete
)
)
)
...and for a specific key i want to get the values, but before i need to validate if there are values. The code is build but i dont know how to validate if there are values inside the array... ive tried isset, empty, count, array_key_exists with no success... i know im close...
$key = 556;
//if there are no formats in array, dont bother to create the ul
if (?????????formats exist in $array[$key]) { ?>
<ul><?php
foreach ($array[$key] as $value) { ?>
<li><?php echo $value['format']; ?></li><?php
} ?>
</ul><?php
} ?>

Call this function as format_exists($array[$key]) which will dig into the value to see if format isset.
function format_exists($values) {
if (!$values || !is_array($values)) return false;
$data = array_shift($values);
return $data && is_array($data) && isset($data["format"]);
}

Try this..
<?php
$key = 556;
$desiredValue = "format";
$subArray = $array[$key];
$arrayForFunction = array_pop($subArray);
if(array_key_exists($desiredValue,$arrayForFunction) && strlen($arrayForFunction[$desiredValue]))
echo "<ul><li>".$arrayForFunction[$desiredValue]."</li></ul>";
?>

Related

How do I get value of specific array element by secondary key?

This has to be easy but I am struggling with it. If the array below exists (named "$startersnames") and I specifically want to echo the value that has "qb" as the key, how do I do that?
I assumed $startersnames['qb'], but no luck.
$startersnames[0]['qb'] works, but I won't know that it's index 0.
Array
(
[0] => Array
(
[qb] => Tannehill
)
[1] => Array
(
[rb] => Ingram
)
[2] => Array
(
[wr] => Evans
)
[3] => Array
(
[wr] => Hopkins
)
[4] => Array
(
[wr] => Watkins
)
[5] => Array
(
[te] => Graham
)
[6] => Array
(
[pk] => Hauschka
)
[7] => Array
(
[def] => Rams
)
[8] => Array
(
[flex] => Smith
)
)
You can use array_column (from php 5.5) like this:
$qb = array_column($startersnames, 'qb');
echo $qb[0];
Demo: http://3v4l.org/QqRuK
This approach is particularly useful when you need to print all the wr names, which are more than one. You can simply iterate like this:
foreach(array_column($startersnames, 'wr') as $wr) {
echo $wr, "\n";
}
You seem to be expecting an array with text keys and value for each, but the array you have shown is an array of arrays: i.e. each numeric key has a value which is an array - the key/value pair where you are looking for the key 'qb'.
If you want to find a value at $array['qb'] then your array would look more like:
$array = [
'qb' => 'Tannehill',
'rb' => 'etc'
];
now $array['qb'] has a value.
If the array you are inspecting is a list of key/value pairs, then you have to iterate over the array members and examine each (i.e. the foreach loop shown in your first answer).
For your multi-dim array, you can loop through the outer array and test the inner array for your key.
function findKey(&$arr, $key) {
foreach($arr as $innerArr){
if(isset($innerArr[$key])) {
return $innerArr[$key];
}
}
return ""; // Not found
}
echo findKey($startersnames, "qb");
You can try foreach loop
$key = "qb";
foreach($startersnames as $innerArr){
if(isset($innerArr[$key])) {
echo $innerArr[$key];
}
}
$keyNeeded = 'qb';
$indexNeeded = null;
$valueNeeded = null;
foreach($startersnames as $index => $innerArr){
//Compare key
if(key($innerArray) === $keyNeeded){
//Get value
$valueNeeded = $innerArr[key($innerArray)];
//Store index found
$indexNeeded = $index;
//Ok, I'm found, let's go!
break;
}
}
if(!empty($indexNeeded) && !empty($valueNeeded)){
echo 'This is your value: ';
echo $startersnames[$indexNeeded]['qb'];
echo 'Or: ':
echo $valueNeeded;
}
http://php.net/manual/en/function.key.php

Returning Php multidimensional array in WordPress

I have the following array stored in the wordpress options table and I need to get the value of each title
a:1:{s:14:"swd_line_items";a:3:{i:0;a:1:{s:5:"title";s:9:"asdfasdfa";}i:1;a:1:{s:5:"title";s:13:"asdf asdf ada";}i:2;a:1:{s:5:"title";s:29:"fffffffffffffffffffffffffffff";}}}
I've tried nested foreach loops but nothing I do seems to work. There must be a simple solution?
function swd_get_line_items() {
$line_items = get_option('line_items_array');
$items = array();
foreach( $line_items as $item => $value ) {
foreach ($value as $new => $v) {
$items[] = array(
$new => $v
);
}
}
return $line_items;
}
Hope this helps :)
$array = unserialize('a:1:{s:14:"swd_line_items";a:3:{i:0;a:1:{s:5:"title";s:9:"asdfasdfa";}i:1;a:1:{s:5:"title";s:13:"asdf asdf ada";}i:2;a:1:{s:5:"title";s:29:"fffffffffffffffffffffffffffff";}}}');
foreach($array['swd_line_items'] as $item) {
echo $item['title'];
}
get_option() perfectly unsezrializes an array so there is no need to do it as the two other answers suggested it.
Then what you have is a two dimensional array but you are perfectly browsing it with two nested foreach.
By the way here is the final output of your code:
As you can see you perfectly extracted the titles:
Array
(
[0] => Array
(
[0] => Array
(
[title] => asdfasdfa
)
)
[1] => Array
(
[1] => Array
(
[title] => asdf asdf ada
)
)
[2] => Array
(
[2] => Array
(
[title] => fffffffffffffffffffffffffffff
)
)
)
But the issue here is that you do not return this array but you return this one:
return $line_items;
Change it into
return $items;
you mean this ?
function swd_get_line_items($serialized_array)
{
$line_items = unserialize($serialized_array);
$items = array();
foreach ($line_items['swd_line_items'] as $key => $item)
{
$items[$key] = $item['title'];
}
return $items;
}

php - How to unset array element in this condition

My array looks like this:
Array (
[0] => Array (
[value] => Array (
[source] => vimeo
[url] => https://vimeo.com/000000
)
[type] => videos
)
[2] => Array (
[value] => 62
[type] => images
)
)
I want to unset the array id with the type => images.
I tried this:
$key = array_search('images',$slides);
unset($slides[$key]);
and it only deletes the first item in the array!!!
Update:
After all, I did it this way:
foreach ( $slides as $slide => $value) {
if ($display_mode == 'images' && $value['type'] == 'videos') {
unset($slides[$slide]);
} elseif ($display_mode == 'videos' && $value['type'] == 'images') {
unset($slides[$slide]);
}
}
Thank you.
foreach ($slides as $key => $slide) {
if (in_array('images', $slide)) unset($slides[$key]);
}
array_search returns false if $needle is not found. false casts to 0 when used as an integer. You might want to consider array_filter for your use case:
$array = array(...);
$array = array_filter($array, function($item) { return in_array('images', $item); });

PHP unsetting array in loop

I am trying to modify an existing array called field_data and delete the parent array of the key->value pair that has control == off. So in this example I would like to unset Array[1]. However it's not working, what am I doing wrong?
foreach ($field_data['0'] as &$subsection) {
foreach ($subsection as $key => $value)
{
if($key=='Control' && $value =='OFF')
{ echo 'match'; unset($subsection); }
}
return $field_data;
}
Field_data
----------
Array
(
[0] => Array
(
[0] => Array
(
[SECTION_ID] =>
[Control] => ON
[1] => Array
(
[SECTION_ID] =>
[Control] => OFF
)
)
)
You're trying to remove a variable that PHP is still using, specifically the array the inner loop is looping over.
The way you're checking you don't even need the inner loop. I would do something like this:
foreach( $field_data[0] as $skey => $svalue ) {
if( array_key_exists('Control', $svalue) && $svalue['Control'] == 'OFF' ) {
unset($field_data[0][$skey]);
}
}
try this...
unset($field_data[0][$subsection]);
I think you shouldn't modify array you're iterating.
Create an array of keys to remove instead, then iterate result and unset keys
$targets = array();
foreach( $field_data[0] as $skey => $svalue ) {
if( array_key_exists('Control', $svalue) && $svalue['Control'] == 'OFF' ) {
targets[] = $skey;
}
foreach($targets as $target)
{
unset($field_data[0][$target]);
}

multi array usage in foreach loop

I've got the following array stored in a $_SESSION
[Bookings] => Array
(
[date] => Array
(
[0] => 1/12/2013
[1] => 1/19/2013
[2] => 2/03/2013
)
[price] => Array
(
[0] => 100
[1] => 150
[2] => 120
)
)
However I want to use a foreach loop and perform calculation on both values within the array.I can't seem to fugure out how I can use the foreach to accomodate multivalues, I've got a sample of a foreach I wrote below of what I'm trying to achieve. Anyone point me in the right direction.
foreach ($_SESSION['Bookings'] as $bookings)
{
myDate = $bookings[date];
myPrice = $bookings[price];
// Some other stuff here
}
foreach ($_SESSION['Bookings']['date'] as $key => $value) {
$myDate = $value;
$myPrice = $_SESSION['Bookings']['price'][$key];
}
simpler I guess :)
foreach (array_keys($_SESSION['Bookings']['date']) as $key)
{
$myDate = $_SESSION['Bookings']['date'][$key];
$myPrice = $_SESSION['Bookings']['price'][$key];
}
Should work?
Some info on: array_keys
just loop through on of your subarrays and read the corresponding value from the other
foreach ( $_SESSION['Bookings'][ 'date' ] as $key => $myDate) {
$myPrice = $_SESSION['Bookings'][ 'price' ][ $key ];
// here you can access to $myDate and $myPrice
// Some other stuff here
}

Categories