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
}
Related
$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");
?>
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);
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
I have an array that looks like this:
[0] => Array
(
[name] => typeOfMusic
[value] => this_music_choice
)
[1] => Array
(
[name] => myMusicChoice
[value] => 9
)
[2] => Array
(
[name] => myMusicChoice
[value] => 8
)
I would like to reform this into something with roughly the following structure:
Array(
"typeOfMusic" => "this_music_choice",
"myMusicChoice" => array(9, 8)
)
I have written the following but it doesn't work:
foreach($originalArray as $key => $value) {
if( !empty($return[$value["name"]]) ){
$return[$value["name"]][] = $value["value"];
} else {
$return[$value["name"]] = $value["value"];
}
}
return $return;
I've tried lots of different combinations to try and get this working. My original array could contain several sets of keys that need converting to arrays (i.e. it's not always going to be just "myMusicChoice" that needs converting to an array) ?
I'm getting nowhere with this and would appreciate a little help. Many thanks.
You just need to loop over the data and create a new array with the name/value. If you see a repeat name, then change the value into an array.
Something like this:
$return = array();
foreach($originalArray as $data){
if(!isset($return[$data['name']])){
// This is the first time we've seen this name,
// it's not in $return, so let's add it
$return[$data['name']] = $data['value'];
}
elseif(!is_array($return[$data['name']])){
// We've seen this key before, but it's not already an array
// let's convert it to an array
$return[$data['name']] = array($return[$data['name']], $data['value']);
}
else{
// We've seen this key before, so let's just add to the array
$return[$data['name']][] = $data['value'];
}
}
DEMO: https://eval.in/173852
Here's a clean solution, which uses array_reduce
$a = [
[
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
],
[
'name' => 'myMusicChoice',
'value' => 9
],
[
'name' => 'myMusicChoice',
'value' => 8
]
];
$r = array_reduce($a, function(&$array, $item){
// Has this key been initialized yet?
if (empty($array[$item['name']])) {
$array[$item['name']] = [];
}
$array[$item['name']][] = $item['value'];
return $array;
}, []);
$arr = array(
0 => array(
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
),
1 => array(
'name' => 'myMusicChoice',
'value' => 9
),
2 => array(
'name' => 'myMusicChoice',
'value' => 8
)
);
$newArr = array();
$name = 'name';
$value = 'value';
$x = 0;
foreach($arr as $row) {
if ($x == 0) {
$newArr[$row[$$name]] = $row[$$value];
} else {
if (! is_array($newArr[$row[$$name]])) {
$newArr[$row[$$name]] = array();
}
array_push($newArr[$row[$$name]], $row[$$value]);
}
$x++;
}
I would like to merge two arrays recursively, leaving associative keys in place, but replace other. I tried using is_numeric() for key checking, but keys '10' and '11' are replaced.
Sample arrays:
Array1:
$arr1['assoc']='foobar';
$arr1[]='test index';
$arr1[][]=array(3,4);
$arr1['10']['test10'][]=array(0,1);
$arr1['11']['test11']=45;
$arr1['multiarray'][]=array(0,1);
Array2:
$arr2[]=1;
$arr2[][]=2;
$arr2['assoc']='test passed';
$arr2['10']['test10'][]=array(0,2);
$arr2['11']['test11']=array(4,5);
$arr2['multiarray'][]=array(0,2);
How to merge them to get this (with a general function):
array(
'assoc' => 'test passed',
0 => 'test index',
1 => array(
0 => array(
0 => 3,
1 => 4,
),
),
10 => array(
'test10' => array (
0 => array(
0 => 0,
1 => 1,
),
1 => array(
0 => 0,
1 => 2,
),
),
),
11 => array(
'test11' => array (
1 => 4,
2 => 5,
),
),
'multiarray' => array(
0 => array(
0 => 0,
1 => 1,
),
1 => array(
0 => 0,
0 => 2,
),
),
2 => 1,
3 => array(
0 => 2,
),
)
Preserving keys' order is not important.
[Edit] Solution:
function array_max_index_key($arr) {
$prev = -1;
if(is_array($arr)) {
$keys = array_keys($arr);
foreach($keys as $k => $key) {
if(is_numeric($key)) {
if($key == $prev+1) {
$prev=$key;
} else break;
}
}
}
return $prev;
}
function justfortesting($a1, $a2) {
$res=$a1;
$max_key=array_max_index_key($res);
if(is_array($a1)) {
foreach ($a2 as $k => $v) {
if(is_numeric($k) && $k<=$max_key) {
$max_key++;
$res[$max_key]=$v;
} elseif (is_array($v)) {
$res[$k]=justfortesting($a1[$k], $v);
} else {
$res[$k]=$v;
}
}
} else {
$res=$a2;
}
return $res;
}
$arr3=justfortesting($arr1, $arr2);
Check for is_string() instead of is_numeric()
Edited:
when you ask for
is_numeric($key)
check for
is_numeric($key) and !is_string($key)