How to delete an element inside a multidimensional array in PHP? - php

I got multidimensional array.
From each subarray, I would like to remove / unset values with price more than 1500.
Array
$item = array(
'phone' => array(
array(
'Item' => 'S5',
'info' => array(
array('seller' => 'John', 'price' => 1800),
array('seller' => 'Mason','price' => 1200),
array('seller' => 'Alex','price' => 1500),
),
),
array(
'Item' => 'iPhone 5',
'info' => array(
array('seller' => 'Depay', 'price' => 1900),
array('seller' => 'David', 'price' => 1450),
array('seller' => 'Daemon', 'price' => 1600),
)
),
),
);
my code:
foreach($item['phone'] as $key =>$price)
{
foreach($price['info'] as $info => $price2 )
{
if ($info['price'] >= 1500)
{
unset($item[$key][$info ]);
}
}
}
Why this code does not work? Can this be done? and if yes... How???
Thanks in advance :-)

You referring to the wrong element level:
foreach($item['phone'] as $key =>$price)
{
foreach($price['info'] as $info => $price2 ) // $price2
{
if ($info['price'] >= 1500) // should be $price2
{
unset($item[$key][$info ]);
}
}
}
You should point into $price2 in your condition:
if ($price2['price'] >= 1500) {
Then, on unsetting, you'll need to point/walk into indices
// write the complete address of this element you want to unset
unset($item['phone'][$key]['info'][$info]);
// ^ ^ don't forget this since they are part of the structure
So all in all:
foreach($item['phone'] as $key =>$price)
{
foreach($price['info'] as $info => $price2 )
{
if ($price2['price'] >= 1500) {
unset($item['phone'][$key]['info'][$info]);
}
}
}
Sample Output

Your code should be like
foreach($item['phone'] as $key => $price) {
foreach($price['info'] as $info => $price2 ) {
if ($price2['price'] >= 1500) {
unset($item['phone'][$key]['info'][$info]);
}
}
}
In if condition you are using key $info, it should be $price2.
Here is the running code https://ideone.com/Mk7VfU

Related

Call each value from array of an object

I have function in class, which returns array with 4 3-4 rows. I have to use each value from related row in table values. I can print builded function atrray, and can print on parent file, but can not get values for elements for each row. Here is my class file:
<?php
class Anyclass
{
public function $monthly($array)
{
.
.
.
}
public function myfunction($array)
{
foreach ($ShowMonths as $duration) {
$array['Credit']['downpayment'] = 0;
$array['Credit']['duration'] = $duration;
$monthly = $this->monthly($array);
$Table['Options'][] = array(
'downpayment' => $array['Credit']['downpayment'],
'duration' => $array['Credit']['duration'],
'monthly' => $monthly,
'total' => $monthly * $array['Credit']['duration'] + $array['Credit']['downpayment']
);
}
print_r($Table);
}
}
Here is my main file
include_once('mypathtofile/FileWithClass.php');
$Cll = new NewOne();
$array = array(
'Rule' => array(
'rule_id' => 1,
'rule_name' => 'Mobile phones',
'interest' => 0.01,
'comission' => 0.01,
'best_offer_downpayment' => 0.5,
'best_offer_duration' => 6
),
'Product' => array(
'product_id' => 1,
'category_id' => 1,
'manufacturer_id' => 1,
'product_price' => 500
),
'Credit' => array(
'downpayment' => 100,
'duration' => 6
)
);
$prtst = $Cll->myfunction($array);
How can I call each elemet for each row?
I'm not sure what you are trying to do, but if you need to get each value in a multidimensional array - you can use recursion:
function get_value($array){
foreach($array as $item){
if(is_array($item)){
get_value($item);
} else {
echo $item;
}
}
}

Extracting value from multidimensional array

$arrayDif = array();
$arrayDif[] = array('employer' => $employer,
'comment' => $comment,
'value' => $resultValue);
Filling in from a loop.
Below is the array that I have filled up. I need to be able to find a match by the 'employer' and 'comment' and extract the value, so I can re-update this value.
Array
(
[0] => Array
(
[employer] => Albury-Wodonga
[comment] => allOtherMembers
[value] => 7
)
[1] => Array
(
[employer] => Albury-Wodonga
[comment] => associateMembers
[value] => 1
)
One command to extract and re-update the value, I suggest to use foreach loop
<?php
$arrayDif = array();
$arrayDif[] = array('employer' => "AAA", 'comment' => "comment 1", 'value' => "1");
$arrayDif[] = array('employer' => "BBB", 'comment' => "comment 2", 'value' => "2");
$arrayDif[] = array('employer' => "CCC", 'comment' => "comment 3", 'value' => "3");
// function for setting the value or returning the value
// notice the $array here is a reference to the real array
function func(&$array, $employer, $comment, $value = ''){
// $v is also a reference
foreach ($array as $k => &$v) {
if($v['employer'] == $employer && $v['comment'] == $comment) {
if(empty($value)) {
return $v['value'];
} else {
$v['value'] = $value;
}
}
}
return "Not Found.";
}
//update
func($arrayDif, 'AAA', 'comment 1', "123123");
//search
echo func($arrayDif, 'AAA', 'comment 1');
?>
Not sure if this is what you are looking for but here you go. I would use a function and simple loop.
<?php
$arrayDif = array();
$arrayDif[] = array(
array('employer' => "Albury-Wodonga", 'comment' => "allOtherMembers", 'value' => "1 star"),
array('employer' => "Employer2", 'comment' => "Good Job", 'value' => "2 stars"),
array('employer' => "Employer3", 'comment' => "Smart", 'value' => "3 stars")
);
// Function for searching the array for the matches and returning the value of the match.
function SearchMe($array, $searchEmployer, $searchComment){
for($i = 0; $i < count($array); $i++){
for($j = 0; $j < count($array[$i]); $j++){
if(
$array[$i][$j]["employer"] == $searchEmployer &&
$array[$i][$j]["comment"] == $searchComment
){
return $array[$i][$j]["value"];
}
}
}
return "No Match";
}
echo SearchMe($arrayDif, "Albury-Wodonga", "allOtherMembers");
?>

unable to delete array key from multidimensional array in cakephp

I want to delete array index which contain rating 0 here is my array
array(
(int) 0 => array(
'Gig' => array(
'id' => '1',
'rating' => (int) 5
)
),
(int) 1 => array(
'Gig' => array(
'id' => '3',
'rating' => (int) 9
)
),
(int) 2 => array(
'Gig' => array(
'id' => '4',
'rating' => '0'
)
)
)
and what I did
for($i = 0; $i<count($agetGigsItem); $i++)
{
if($agetGigsItem[$i]['Gig']['rating']==0)
{
unset($agetGigsItem[$i]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
i also try foreach loop but unable to resolve this issue.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) { unset($agetGigsItem[$key]); }
}
I think you need to reupdate your array.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] != 0)
{
unset($agetGigsItem[$key]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
I hope you are missing $this and so you cannot access the array in CakePHP.
So try this:
foreach ($this->$agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->$agetGigsItem[$key]);
}
}
This code will unset arrey index with value 0.
<?php
$array=array(
array(
'Gig' => array(
'id' => '1',
'rating' =>5
)
),
array(
'Gig' => array(
'id' => '3',
'rating' =>9
)
),
array(
'Gig' => array(
'id' => '4',
'rating' =>0
)
)
);
foreach($array as $a){
if($a['Gig']['rating']==0){
unset($a['Gig']['rating']);
}
$array1[]=$a;
}
var_dump($array1);
Destroying occurances within an array you are actually processing over with a for or a foreach is always a bad idea. Each time you destroy an occurance the loop can easily get corrupted and get in a terrible mess.
If you want to remove items from an array it is better to create a copy of the array and process over that new array in the loop but remove the items from the original array.
So try this instead
$tmparray = $this->agetGigsItem; // will copy agetGigsItem into new array
foreach ($tmparray as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->agetGigsItem[$key]);
}
}
unset($tmparray);

How to check if a value exists in a Multidimensional array

I have an Multidimensional array that takes a similar form to this array bellow.
$shop = array( array( Title => "rose",
Price => 1.25,
Number => 15
),
array( Title => "daisy",
Price => 0.75,
Number => 25,
),
array( Title => "orchid",
Price => 1.15,
Number => 7
)
);
I would like to see if a value I'm looking for is in the array, and if so, return the position of the element in the array.
Here's a function off the PHP Manual and in the comment section.. Works like a charm.
<?php
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Found this function in the PHP docs: http://www.php.net/array_search
A more naive approach than the one showed by Zander, you can hold a reference to the outer key and inner key in a foreach loop and store them.
$outer = "";
$inner = "";
foreach($shop as $outer_key => $inner_array){
foreach($inner_array as $inner_key => $value) {
if($value == "rose") {
$outer = $outer_key;
$inner = $inner_key;
break 2;
}
}
}
if(!empty($outer)) echo $shop[$outer][$inner];
else echo "value not found";
You can use array_map with in_array and return the keys you want
$search = 1.25;
print_r(
array_filter(array_map(function($a){
if (in_array($search, $a)){
return $a;
}
}, $shop))
);
Will print:
Array
(
[0] => Array
(
[Title] => rose
[Price] => 1.25
[Number] => 15
)
)
php >= 5.5
$shop = array( array( 'Title' => "rose",
'Price' => 1.25,
'Number' => 15
),
array( 'Title' => "daisy",
'Price' => 0.75,
'Number' => 25,
),
array( 'Title' => "orchid",
'Price' => 1.15,
'Number' => 7
)
);
$titles = array_column($shop,'Title');
if(!empty($titles['rose']) && $titles['rose'] == 'YOUR_SEARCH_VALUE'){
//do the stuff
}

how to find a element in a nested array and get its sub array index

when searching an element in a nested array, could i get back it's 1st level nesting index.
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
/* i want the sub array index to be returned */
}
}
?>
i.e to say, if i'am searching 'victor', i would like to have 'dep1' as the return value.
Could anyone help ??
Try:
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);
/* These will be used to keep a record of the
current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found
foreach ($iter as $k=>$val) {
//if dep1 matches, record it until it shifts to dep2
if($k === $parent_keys[$parent_index]){
$parent = $k;
//making sure the counter is not incremented
//more than the number of elements present
($parent_index<$size-1)?$parent_index++:'';
}
if ($val == $name) {
//if the value is found, set flag and break the loop
$flag = 1;
break;
}
}
($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;
Demo
This works , but I don't know if you are ok with this...
<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );
foreach($col2 as $k=>$arr)
{
foreach($arr as $k1=>$arr2)
{
if(in_array($name,$arr2))
{
echo $k;
break;
}
}
}
OUTPUT :
dept2
Demo

Categories