array_search does not work properly in foreach - php

For some reason when I put this array through foreach it does not work properly.
What am I doing wrong?
array (size=2)'Final' => array (size=1)'sender' => array (size=1)'asd' => array (size=2)...'Hos' => array (size=1)'sender' => array (size=1)'asd' => array (size=2)...
foreach($sent_app_groups['title'] as $k => $v) {
$pill_title = array_search($sent_app_groups['title'][$k],$sent_app_groups['title']);
echo $pill_title;
}
The result should be:
Final Hos
But I always get:
Final Final

I guess this is the right way to do it, silly me :P
But still I don't get it, shouldn't it do the same thing with array_search?
foreach($sent_app_groups['title'] as $k => $v) {
$pill_title = $k;
echo $pill_title;
}

Related

Multidimensional array loop to get value

I have an array of multiple arrays all with different levels. What im trying to do is loop though the array by key, and it will go through each level getting the values for those keys. myArray looks something like this
Array ( [0] =>
Array ( [Date] => 2011-15-22
[Color] => blue
[Status] => Fresh
[1] =>
Array ( [Date] => 1999-08-04
[Color] => green
[Status] => Rotten) )
I have tried
foreach($myArray as $row){
foreach($row["Date"] as $k){
echo $k
}
}
I am getting an
Notice: Undefined index: Date
and
Warning: Invalid argument supplied for foreach()
Simply with array_walk_recursive function:
$arr = [
[ 'Date' => '2011-15-22', 'Color' => 'blue', 'Status' => 'Fresh' ],
[ 'Date' => '1999-08-04', 'Color' => 'green', 'Status' => 'Rotten' ]
];
array_walk_recursive($arr, function($v, $k){
if ($k == 'Date') echo $v . PHP_EOL;
});
The output:
2011-15-22
1999-08-04
On your foreach, you should specify the key and value so you can access both:
foreach ($myArray as $key => $value){
echo $key.' is '. gettype ($value).'<br>';
if (is_array($value)){
foreach ($value as $subKey => $subValue){
echo $subkey . ' => ' . $subValue . '<br>';
}
}
}
This way you can access and print all values without losing the structure
As axiac states in the comments, $row["Date"]is a String and therefore not iterable. You probably just want this:
foreach($myArray as $row){
foreach($row as $k){
echo $k
}
}
The Notice Undefined index: Date also describes what is going wrong - you are accessing the index without checking if it exists. It does look like that your data structure is not always the same. In this case you should always check the existence with the isset function:
if (isset($row["Date"])) {
//do something here
}
It looks like you just need this:
foreach($myArray as $row){
echo $row["Date"];
}
or
foreach($myArray as $row){
$k= $row["Date"];
//do stuff...
}
or
foreach($myArray as $row){
$k[]= $row["Date"];
}
// do stuff with $k[] array.
Warning: Invalid argument supplied for foreach()
Because $row["Date"] is string
foreach() - foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.
Notice: Undefined index: Date
Probably your array may not have element with key Date somewhere (your array structure probably different, as iteration takes place), so you are getting this message, use isset() to or array_key_exists() to validate, depending on the purpose.
Please note isset != array_key_exists
$a = array('key1' => 'test1', 'key2' => null);
isset($a['key2']); // false
array_key_exists('key2', $a); // true
There is another important difference. isset doesn't complain when $a does not exist, while array_key_exists does.

PHP Arrays Values

Please provide help on how to write array values if I have array like this:
Array (
[937245328] => $0.79
[310776983] => $0.53
[720315389] => $0.39
[310800933] => $0.30
[1011934667] => $0.28
[1576813623] => $0.21
[926978479] => $0.19
[1011934570] => $0.14
[937244096] => $0.14
[310777321] => $0.13
[384801319] => $0.13
[519987816] => $0.12
[992123310] => $0.11
)
I would like to print this array out somelike this:
937245328: $0.79
310776983: $0.53
720315389: $0.39
and so on... Thanks for any help.
if your array is called
$myArray
Then you can print it out as follows:
<?php
foreach ($myArray as $key => $value)
{
echo $key.": ".$value."<br>";
}
?>
Let me know if that worked for you! :)
You can print the array (the key and the value) using foreach loop.
<?php
$dolla = Array (
'937245328' => '$0.79',
'310776983' => '$0.53',
'720315389' => '$0.39'
);
foreach($dolla as $key => $value) {
echo $key.": ".$value."<br>";
}
?>

PHP Remove Multidimensional Array Value

I have array multidimensional code like this:
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
unset($array[$eaten]);
and what i need is to delete 'grape' from the array because 'grape' already eaten. how to fix my code to unset the 'grape'?
and my question number two, if it can be unset, is there a way to unset multi value like
unset($array,['grape','orange']);
thanks for help..
You can remove eaten element by following way. Use array_search() you can find key at the position of your eaten element.
Here below code shows that in any multidimensional array you can call given function.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
$array = removeElement($array, $eaten);
function removeElement($data_arr, $eaten)
{
foreach($data_arr as $k => $single)
{
if (count($single) != count($single, COUNT_RECURSIVE))
{
$data_arr[$k] = removeElement($single, $eaten);
}
else
{
if(($key = array_search($eaten, $single)) !== false)
{
unset($data_arr[$k][$key]);
}
}
}
return $data_arr;
}
P.S. Please note that you can unset() multiple elements in single call. But the way you are using unset is wrong.
Instead of using unset() i suggest you to create a new Array after removal of required value benefit is that, your original array will remain same, you can use it further:
Example:
// your array
$yourArr = array(
'fruits'=>array('apple','orange','grape', 'pineaple'),
'vegetables'=>array('tomato', 'potato')
);
// remove array that you need
$removeArr = array('grape','tomato');
$newArr = array();
foreach ($yourArr as $key => $value) {
foreach ($value as $finalVal) {
if(!in_array($finalVal, $removeArr)){ // check if available in removal array
$newArr[$key][] = $finalVal;
}
}
}
echo "<pre>";
print_r($newArr);
Result:
Array
(
[fruits] => Array
(
[0] => apple
[1] => orange
[2] => pineaple
)
[vegetables] => Array
(
[0] => potato
)
)
Explanation:
Using this array array('grape','tomato'); which will remove the value that you define in this array.
This is how I would do it.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$unset_item = 'grape';
$array = array_map(function($items) use ($unset_item) {
$found = array_search($unset_item, $items);
if($found){
unset($items[$found]);
}
return $items;
}, $array);

How to unset dynamically generated multidimensional array

I am trying to delete an array whereby one of its values..(time) meet a specific condition. \The code I'm currently working with looks like this:
foreach($_SESSION as $key) {
foreach($key['time'] as $keys=>$value){
if(condition){
unset($key);
}
}
}
The array looks like this.
Array
(
[form1] => Array
(
[hash] => lFfKBKiCTG6vOQDa8c7n
[time] => 1401067044
)
[form5] => Array
(
[hash] => TTmLVODDEkI1NrRnAbfB
[time] => 1401063352
)
[form4] => Array
(
[hash] => XCVOvrGbhuqAZehBmwoD
[time] => 1401063352
)
I tried to adapt solutions from these pages but didn't work.
Remove element in multidimensional array and save
PHP - unset in a multidimensional array
PHP How to Unset Member of Multidimensional Array?
If you want to unset the values inside it, a simple single foreach will suffice. Consider this example:
$values = array(
'form1' => array('hash' => 'lFfKBKiCTG6vOQDa8c7n', 'time' => 1401067044),
'form5' => array('hash' => 'TTmLVODDEkI1NrRnAbfB', 'time' => 1401063352),
'form4' => array('hash' => 'XCVOvrGbhuqAZehBmwoD', 'time' => 1401063352),
);
$needle = 1401067044;
foreach($values as $key => &$value) {
if($value['time'] == $needle) {
// if you want to remove this key pair use this
unset($values[$key]['time']);
// if you just want to remove the value inside it
$value['time'] = null;
// if you want to remove all of this entirely
unset($values[$key]);
}
}
Fiddle
Unsetting in a for loop can lead to issues, its easier and better to use array_filter which is optimized for this kind of problem. Here is how to do it with your example. ideone running code
<?php
$ar = Array(
"form1" => Array
(
"hash" => 'lFfKBKiCTG6vOQDa8c7n',
"time" => '1401067044'
),
"form5" => Array
(
"hash" => 'TTmLVODDEkI1NrRnAbfB',
"time" => '1401063352'
),
"form4" => Array
(
"hash" => 'XCVOvrGbhuqAZehBmwoD',
"time" => '1401063352'
)
);
$condition = '1401067044';
$newArray = array_filter($ar, function($form) use ($condition) {
if (!isset($form['time'])) {
return true;
}
return $form['time'] != $condition;
});
var_export($newArray);
array_filter
Assuming your values are stored in $_SESSION
foreach($_SESSION as $key => $value) {
if(isset($value['time']) && $value['time'] < 1401063352) {
unset($_SESSION[$key]);
}
}
If you are storing your values in $_SESSION you may want to consider storing them in a subfield like $_SESSION['myForms'] so if you need to add other values to your session you can easily access only the values you need.
You need to do
unset($_SESSION[$key])
However as mentioned by Victory, array_filter is probably a better approach to this.

str_replace keys in multidimensional array PHP

I have a multidimensional array like the following:
Array (
[results] => Array (
[0] => Array (
[object_id] => 13
[id] => 13
[idno] => e00110-o00005-2010-PROG
[display_label] => La Bohème / PUCCINI - 2010
[ca_objects.description] => Libreto de Luigi Illica y Giuseppe Giacosa basado en Escenas de la vida bohemia de Henri Murger Nueva producción – Teatro Colón
[ca_objects.type_id] => Programa de mano
)
//more data here
I'm trying to loop the array and replace "object_id" key for "new_id" using str_replace.
$str="object_id";//The string to search for
$rep="new_id";//The replacement string
foreach ($array as $value) {
foreach ($value as $key2 => $value2) {
foreach ($value2 as $key3 => $value3) {
str_replace($str,$rep,$key3);
echo $key3." : ".$value3."<br>"; //It gets printed with no changes
}
}
}
The above code does not work, can you see what am I doing wrong?.
I tried using strings instead of variables but didn't work either.
Thanks in advance.
...if you really want to use str_replace():
$array['results'] = array_map(function($item){
$keys = implode(',', array_keys($item));
$keys = str_replace('object_id', 'new_id', $keys);
return array_combine(explode(',', $keys), array_values($item));
}, $array['results']);
The other way - create a new array, then iterate over the old array and assign values from it to the new array, while changing the keys you want:
$array['results'] = array_map(function($item){
$item['new_id'] = $item['object_id'];
unset($item['object_id']);
return $item;
}, $array['results']);
(this one will reorder the array, if it matters)
foreach ($array as &$value) {
foreach ($value as $key2 => &$value2) {
$value2[$rep] = $value2[$str];
unset($value2[$str]);
}
}
It's necessary to iterate over the arrays using references so that the modifications affect the original array, not a copy.
#One Trick Pony:
I followed your suggestion and created a new array. It was exactly what I needed and I did it by myself!!. Following code creates the new array. Thank you all so much for helping me!
$display=array();
foreach ($array as $value) {
foreach ($value as $value2) {
$display [] = array (
'Id del objeto' => $value2['object_id'],
'Título' => $value2['display_label'],
'Descripción' => $value2['ca_objects.description'],
);
}
}

Categories