php - How to unset array element in this condition - php

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); });

Related

How to fetch non-empty Array from an Array

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;
});

Modify a value by function call if its key ends with a specific word

I need to change all the values for a matching key within an associative array using php but I can only target the key by matching a specific string within the key and not the entire key name as it may change.
In the case below, I need a way to target all the "_file" keys and change their filenames to a related attachment ID but targeting the entire key "bg_infographic_file" won't be possible as the key may change to "bg_whitepaper_file" or some other name.
Current $resources array:
Array
(
[0] => Array
(
[bg_infographic_title] => Logo Upload
[bg_infographic_file] => logomark-large-forVector.png
)
[1] => Array
(
[bg_infographic_title] => Profile Image
[bg_infographic_file] => ProfilePic.jpg
)
[2] => Array
(
[bg_infographic_title] => Document Upload
[bg_infographic_file] => Test_PDF.pdf
)
)
What I need as a result:
Array
(
[0] => Array
(
[bg_infographic_title] => Logo Upload
[bg_infographic_file] => 86390
)
[1] => Array
(
[bg_infographic_title] => Profile Image
[bg_infographic_file] => 99350
)
[2] => Array
(
[bg_infographic_title] => Document Upload
[bg_infographic_file] => 67902
)
)
I'm thinking of something along these lines but I can't quite figure it out as the following simply returns the unchanged array data:
foreach( $resources as $key=>$value ) {
if( strpos($key, '_file') !== FALSE ) {
$value = get_image_id_from_url($value);
}
}
Thanks for all your help!
Do it like this, instead:
foreach ($resources as $key => $value) {
foreach ($value as $subKey => $subValue) {
if (substr($subKey, -5) == '_file') {
$resources[$key][$subKey] = get_image_id_from_url($subValue);
}
}
}
The first issue is that you have an array of arrays, and you were only looping through the outer array. The second issue is that $value can't be modified inside the foreach() loop in this way. We can also use substr($key, -5) == '_file' to make sure '_file' is at the end of the string.
$findMe = "_file";
foreach ($resources as $key => $value) {
foreach ($value as $findInMe => $fileName) {
$pos = strpos($findInMe, $findMe);
if ($pos !== false) {
$resources[$key][$findInMe] = get_image_id_from_url($fileName);
}
}
}

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]);
}

Get to leaf in multidimension array

I have array structure where i must get leaf.
Example
First type of array
[name] => long_desc
[values] => Array
(
[0] => Array
(
[values] => xxx
)
)
)
or
(
[name] => long_desc
[values] => Array
(
[0] => Array
(
[name] => span
[values] => Array
(
[0] => Array
(
[values] => xxx
)
)
)
How to get value what name xxx? My array have longer depth and using foreach many times not work fine. I was try recursivearrayiterator but not help.
Try array_walk_recursive() function:
function testArrayItem($item, $key)
{
if ( $item == "xxx" ) {
echo "Found xxx on key {$key}";
}
}
array_walk_recursive($array, 'testArrayItem');
EDIT:
If you want to get entire branch, which leads to the leaf you can recursively iterate through it:
function getPathToLeafRecursive(array $input, array &$branch)
{
foreach ( $input as $key => $item ) {
if ( 'xxx' == $item ) {
$branch[] = $key;
return true;
}
if ( is_array($item) ) {
$res = getPathToLeafRecursive($item, $branch);
if ( $res ) {
$branch[] = $key;
return true;
}
}
}
return false;
}
$found_branch = array();
getPathToLeafRecursive($array, $found_branch);
$found_branch = array_reverse($found_branch);
var_export($found_branch);
Here's how to find the leaf node, without depending on the name of the key. It's rather primitive and could use some OOP, but it demonstrates the basic algo:
$array = array(
array('name' => 'span',
'values' => array('values' => 'xxx', array('values' => 'yyy')),
'stuff' => '123'
)
);
$deepest_depth = 0;
$deepest_node = null;
find_leaf($array, 0);
function find_leaf($array, $current_depth) {
global $deepest_depth, $deepest_node;
do {
$current_node = current($array);
if (is_array($current_node)) {
find_leaf($current_node, $current_depth+1);
} else {
if ($deepest_node === null || $current_depth > $deepest_depth) {
$deepest_depth = $current_depth;
$deepest_node = $current_node;
}
}
next($array);
} while ($current_node !== FALSE);
}
echo $deepest_node;
What is this xxx value? Do you know the content and you just want to know that it is in the Array?
In that case you can use the RecursiveArrayIterator with the RecursiveFilterIterator.
If you want to get all "values" keys that are leafs, then you can use the RecursiveFilterIterator too, but checking for "values" that are scalar for example.

how to check if values exist inside a multidimensional array

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>";
?>

Categories