Unset index of an array inside another array - php

I have an array with in which there is another array. I need to unset a index of the sub array.
array
0 =>
array
'country_id' => string '1' (length=1)
'description' => string 'test' (length=4)
1 =>
array
'country_id' => string '2' (length=1)
'description' => string 'sel' (length=5)
2 =>
array
'country_id' => string '3' (length=1)
'description' => string 'soul' (length=5)
Now i need to unset country_id of all the three index of the master array. I am using PHP and I initially thought unset will do until i realized my array is nested.
How can I do this?

foreach ($original_array as &$element) {
unset($element['country_id']);
}
why &$element?
Because foreach (...) will perform a copy, so we need to pass the reference to the "current" element in order to unset it (and not his copy)

foreach($yourArray as &$arr)
{
unset($arr['country_id']);
}

foreach ($masterArray as &$subArray)
unset($subArray['country_id']);
The idea is that you take each sub array by reference and unset the key within that.
EDIT: another idea, just to make things interesting, would be to use the array_walk function.
array_walk($masterArray, function (&$item) { unset ($item['country_id']); });
I'm not sure that it's any more readable, and the function call will make it slower. Still, the option is there.

You need to use:
foreach ($array as &$item) {
unset($item['country_id']);
}
but after loop you should really unset reference otherwise you might get into trouble so the correct code is:
foreach ($array as &$item) {
unset($item['country_id']);
}
unset($item);

Related

Accessing Multi dimensional array object in PHP

I have an item object in PHP, which has the following structure on var_dump :
$item->properties:
array (size=1)
1 =>
array (size=4)
'Key1' => string 'Value1' (length=6)
'Key2' => int 1
'Key3' => string 'true' (length=4)
'Key4' => string 'true' (length=4)
I want to access Key, value in a foreach loop and assign Key, value pair to some internal variables, however when i am using the foloowing code to loop pver array of array, i am getting error in accessing the values in the way i want. Here is what i am doing :
foreach($item->properties as $property) {
foreach($property as $value) {
echo $value;
}
}
Anyone have an idea what am i doing wrong, and how can i fix that ?
one of the things you provide to the foreach isn't a a valid argument, as the error says. Find out which of the 2 it is (linenumber) and var_dump that argument to see what type it is (probably "not an array" ).
In the end either $item->properties itself, or the array values of that array (if it is one), so $property is not an array.
It could be, for instance, that maybe the first key of the properties IS an array, but the second isn't? then you could use is_array to check.

Remove deeply nested element from multi-dimensional array?

I need to remove an element form a deeply nested array of unknown structure (i.e. I do not know what the key sequence would be to address the element in order to unset it). The element I am removing however does have a consistent structure (stdObject), so I can search the entire multidimensional array to find it, but then it must be removed. Thoughts on how to accomplish this?
EDIT: This is the function I have right now trying to achieve this.
function _subqueue_filter_reference(&$where)
{
foreach ($where as $key => $value) {
if (is_array($value))
{
foreach ($value as $filter_key => $filter)
{
if (isset($filter['field']) && is_string($filter['field']) && $filter['field'] == 'nodequeue_nodes_node__nodequeue_subqueue.reference')
{
unset($value[$filter_key]);
return TRUE;
}
}
return _subqueue_filter_reference($value);
}
}
return FALSE;
}
EDIT #2: Snipped of array structure from var_dump.
array (size=1)
1 =>
array (size=3)
'conditions' =>
array (size=5)
0 =>
array (size=3)
...
1 =>
array (size=3)
...
2 =>
array (size=3)
...
3 =>
array (size=3)
...
4 =>
array (size=3)
...
'args' =>
array (size=0)
empty
'type' => string 'AND' (length=3)
...so assuming that this entire structure is assigned to $array, the element I need to remove is $array[1]['conditions'][4] where that target is an array with three fields:
field
value
operator
...all of which are string values.
This is just a cursor problem.
function recursive_unset(&$array)
{
foreach ($array as $key => &$value) # See the added & here.
{
if(is_array($value))
{
if(isset($value['field']) && $value['field'] == 'nodequeue_nodes_node__nodequeue_subqueue.reference')
{
unset($array[$key]);
}
recursive_unset($value);
}
}
}
Notes : you don't need to use is_string here, you can just make the comparison as you're comparing to a string and the value exists.
Don't use return unless you're sure there is only one occurrence of your value.
Edit :
Here is a complete example with an array similar to what you showed :
$test = array (
1 => array (
'conditions' =>
array (
0 => array ('field' => 'dont_care1', 'value' => 'test', 'operator' => 'whatever'),
1 => array ('field' => 'dont_care2', 'value' => 'test', 'operator' => 'whatever'),
2 => array ('field' => 'nodequeue_nodes_node__nodequeue_subqueue.reference', 'value' => 'test', 'operator' => 'whatever'),
3 => array ('field' => 'dont_care3', 'value' => 'test', 'operator' => 'whatever')
),
'args' => array (),
'type' => 'AND'
));
var_dump($test);
function recursive_unset(&$array)
{
foreach ($array as $key => &$value)
{
if(is_array($value))
{
if(isset($value['field']) && $value['field'] == 'nodequeue_nodes_node__nodequeue_subqueue.reference')
{
unset($array[$key]);
}
recursive_unset($value);
}
}
}
recursive_unset($test);
var_dump($test);
One way to solve this was to extend your recursive function with a second parameter:
function _subqueue_filter_reference(&$where, $keyPath = array())
You'd still do the initial call the same way, but the internal call to itself would be this:
return _subqueue_filter_reference($value, array_merge($keyPath, array($key)));
This would provide you with the full path of keys to reach the current part of the array in the $keyPath variable. You can then use this in your unset. If you're feeling really dirty, you might even use eval for this as a valid shortcut, since the source of the input you'd give it would be fully within your control.
Edit: On another note, it may not be a good idea to delete items from the array while you're looping over it. I'm not sure how a foreach compiles but if you get weird errors you may want to separate your finding logic from the deleting logic.
I have arrived at a solution that is a spin-off of the function found at http://www.php.net/manual/en/function.array-search.php#79535 (array_search documentation).
Code:
function _subqueue_filter_reference($haystack,&$tree=array(),$index="")
{
// dpm($haystack);
if (is_array($haystack))
{
$result = array();
if (count($tree)==0)
{
$tree = array() + $haystack;
}
foreach($haystack as $k=>$current)
{
if (is_array($current))
{
if (isset($current['field']) && is_string($current['field']) && $current['field'] == 'nodequeue_nodes_node__nodequeue_subqueue.reference')
{
eval("unset(\$tree{$index}[{$k}]);"); // unset all elements = empty array
}
_subqueue_filter_reference($current,$tree,$index."[$k]");
}
}
}
return $tree;
}
I hate having to use eval as it SCREAMS of a giant, gaping security hole, but it's pretty secure and the values being called in eval are generated explicitly by Drupal core and Views. I'm okay with using it for now.
Anyway, when I return the tree I simply replace the old array with the newly returned tree array. Works like a charm.

PHP - 2D Arrays - Looping through array keys and retrieving their values?

I have an array that outputs like this:
1 =>
array
'quantity' => string '2' (length=1)
'total' => string '187.90' (length=6)
2 =>
array
'quantity' => string '2' (length=1)
'total' => string '2,349.90' (length=8)
I would like to loop through each array keys and retrieve the set of 3 values relating to them, something like this (which doesnt work):
foreach( $orderItems as $obj=>$quantity=>$total)
{
echo $obj;
echo $quantity;
echo $total;
}
Would someone be able to give some advice on how I would accomplish this, or even a better way for me to be going about this task. Any information relating to this, including links to tutorials that may cover this, would be greatly appreciated. Thanks!!
foreach( $orderItems as $key => $obj)
{
echo $key;
echo $obj['quantity'];
echo $obj['total'];
}
Using the above.
You need to read the docs on forEach() a little more, since your syntax and understanding of it is somewhat incorrect.
$arr = array(
array('foo' => 'bar', 'foo2', 'bar2'),
array('foo' => 'bar', 'foo2', 'bar2'),
);
foreach($arr as $sub_array) {
echo $sub_array['foo'];
echo $sub_array['bar'];
}
forEach() iteratively passes each key of the array to a variable - in the above case, $sub_array (a suitable name, since your array contains sub-arrays). So within the loop body, it's that you need to interrogate.

using reference (&) in foreach add `&` in output array? is it a bug

I am using PHP 5.3.5, and I am stuck with an error. I have an array
$input = array(
0=>array(
'a'=>'one0',
'b'=>'two0',
'c'=>'three0',
'd'=>'four0',
'e'=>'five0'
),
1=>array(
'a'=>'one1',
'b'=>'two1',
'c'=>'three1',
'd'=>'four1',
'e'=>'five1'
)
);
I use array_splice to remove the initial two values from each array
by using &(value by reference) in foreach
foreach ($input as $bk => &$bv) {
$op[]=array_splice($bv,0,2);
}
Now when I see the $input then it adds a & just before the second array.
var_dump($input); shows this
array
0 =>
array
'c' => string 'three0' (length=6)
'd' => string 'four0' (length=5)
'e' => string 'five0' (length=5)
1 => & <====================================From where this `&` comes?
array
'c' => string 'three1' (length=6)
'd' => string 'four1' (length=5)
'e' => string 'five1' (length=5)
Where does & come from and how does it produce such array? Is it valid?
If I remove & in the foreach, it does not gives me desired array. Am I doing something wrong?
It's pretty counter-intuitive but it isn't actually a bug. When you use references in a loop, you're advised to unset the reference right after the loop:
foreach ($input as $bk => &$bv) {
$op[]=array_splice($bv,0,2);
}
unset($bv);

How to get content from array

I'm total newbie to PHP and Drupal but I fix this simple(?) thingo on my template. I want to get title, date, text and link path from this array? I can't get it out of there. I think its because its in inside of another array and because im noob in PHP I cant get it out of there ? Also I would like to get it to a loop. If theres more content, I would get it as a list or something. I would use foreach for this? Like foreach $contents as $content and so on?
I get this output from this: var_dump($contents);
array
'total' => string '1' (length=1)
'data' =>
array
0 =>
array
'cid' => string '13231' (length=3)
'title' => string 'TITLEBLABLABLA' (length=3)
'body_text' => string 'TEXTBLABLABAL' (length=709)
'created' => string '313131' (length=10)
'created' => string '2010-07-13 14:12:11' (length=19)
'path' => string 'http://goog.fi' (length=72)
Think of accessing multidimensional arrays in the same way you'd access a file in a subdirectory: just reference each level/directory in sequence. Assuming that array is stored in $arr, you'd get the title as follows:
$arr['data']['0']['title']
Here is a basic PHP array tutorial
It comes down to this:
You retrieve an element of an array with []
$array = array( 'a' => 'b');
echo $array['a']; //Prints b;
To loop through a multi-dimensional array and echo date try this...
foreach ($contents as $key => $content) {
echo $content[$key]['created'];
}
If that doesn't work, post the output of print_r($content) in your question so I can't build you exact array. I'm kinda confused over the structure of your array in your question.

Categories