Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
If I have an array like this:
$cars = array (
array("name"=>"jeep","Year"=>"2012"),
array("name"=>"ferrari","Year"=>"2017"),
array("name"=>"jaguar","Year"=>"2013")
);
How to print a $cars['name'] where $cars[Year] = 2013, is that possible in the array as we can do in MySQL? As we know with MySQL we can do:
select * from table where //condition
So, how this can be done in arrays?
You could loop through each element in the array and using an 'if' statement echo the name of the car if the year is 2013
$cars = array (
array("name"=>"jeep","Year"=>"2012"),
array("name"=>"ferrari","Year"=>"2017"),
array("name"=>"jaguar","Year"=>"2013")
);
foreach ($cars as $value) {
if($value[Year] == 2013){
echo $value[name] ."<br>";
}
}
And also solution with array_filter, because you will probably have multiple cars with same year.
$cars = array (
array("name"=>"jeep","Year"=>"2012"),
array("name"=>"ferrari","Year"=>"2017"),
array("name"=>"jaguar","Year"=>"2013")
);
$filtered_cars = array_filter($cars, function ($item) {
return $item['Year'] === '2013';
});
print_r(current($filtered_cars)['name']);
An example with the isFromYear function accepting the year as a parameter:
<?php
$cars = array (
array("name"=>"jeep","Year"=>"2012"),
array("name"=>"ferrari","Year"=>"2017"),
array("name"=>"jaguar","Year"=>"2013")
);
class YearFilter {
private $year;
function __construct($year) {
$this->year = $year;
}
function isFromYear($i) {
return $i["Year"] == $this->year;
}
}
$matches = array_filter($cars, array(new YearFilter("2013"), 'isFromYear'));
print_r($matches);
?>
You can use array_filter() and pass an conditional function as the second argument along with your array. As an example in your case:
function filterArray($value){
if($value['Year'] == "2013")
return $value['name'];
}
$filteredArray = array_filter($fullArray, 'filterArray');
So if we passed an array that looks like:
$fullArray = array (
array("name"=>"John","Year"=>"2012"),
array("name"=>"Doe","Year"=>"2017"),
array("name"=>"Martin","Year"=>"2013")
);
Output would be:
Array
(
[2] => Array
(
[name] => Martin
[Year] => 2013
)
)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have an array with different extension's values, Now i want check whether '.csv' is IN this Array or not . If it is then whats the name.
Ex: - Array
(
[0] => xyz.mp4
[1] => bulk_sample.csv
[2] => abc.avi
[3] => pqr.3gp
)
Here 'abc.csv' is available in array. and name should be in $name='abc.csv';
Simple "one-line" solution using preg_grep function:
$names = preg_grep("/\.csv$/i", $val);
print_r($names);
The output:
Array
(
[3] => abc.csv
)
Note, that hypothetically there could be multiple .csv items
Try this code :
In this foreach loop is checking for sub string which is .csv for all elements in array.
<?php
$array =array('test.mp4','abc.avi','xyz.3gp','abc.csv');
$flag=false;
$filename="";
foreach($array as $check) {
$place = strpos($check, ".csv");
if ($place>0) {
$flag=true;
$filename=$check;
break;
} else {
$flag=false;
}
}
if($flag){
echo "File Name:".$filename;
}else{
echo "not found any .csv in array"."<br>";
}
?>
Note: it will return first found name with .csv extension.
This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 6 years ago.
I have two functions that I am working with. The first one does a database call and grabs two attributes of a user. The UserID and Markup for that user.
/*
Search Markup for a specific QID
*/
function searchMarkup($identifier){
global $markupArray;
if(isset($markupArray)){
foreach($markupArray as $m){
if((string)$key->QID == (string)$identifier){
return $m->markup;
}
}
}
return '';
}
/*
Fetch the markup data for this dashboard
*/
function fetchMarkup(){
global $dashboardID;
global $markupArray;
$objDB = new DB;
$objMarkup = $objDB
-> setStoredProc('FetchMarkup')
-> setParam('dashboardID', $dashboardID)
-> execStoredProc()
-> parseXML();
// Create an array of the markup
if(isset($objMarkup->data)){
$i = 0;
foreach($objMarkup->data as $m){
$markup[$i] = array();
$markup[$i]['QID'] = (string)$m->QID;
$markup[$i]['markup'] = (string)$m->Markup;
$i++;
}
$markupArray = $markup;
}
}
When I run fetchMarkup() and then print out $markupArray, I get the result of:
Array
(
[0] => Array
(
[QID] => Q0002
[markup] => success
)
[1] => Array
(
[QID] => Q101
[markup] => success
)
[2] => Array
(
[QID] => Q200
[markup] => info
)
)
My next step is to be able to search that array by providing a QID and having it return the markup value to me.
I am trying to so something like searchMarkup('Q0002') to have it tell me the result of markup but I am not getting any response.
How could I go about retrieving the value of markup from the array that is created by fetchMarkup() ?
why you are using $key ? which came from no where
foreach($markupArray as $m)
as you can see you alias $m not $key
And $markupArray is an associated array not an object array
So instead of
if((string)$key->QID == (string)$identifier){
return $m->markup;
}
since it is an associated array change it to
if((string)$key['QID'] == (string)$identifier){
return $m['markup'];
}
So your searchMarkup would be like this
function searchMarkup($identifier){
global $markupArray;
if(isset($markupArray)){
foreach($markupArray as $m){
if((string)$m['QID'] == (string)$identifier){
return $m['markup'];
}
}
}
return '';
}
Demo
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Heres what I want to do:
<?php
$array = array("array1" => array(), "array2" => array());
function mdparser(){
for($i = 0;$i < func_num_args();$i++){
//foreach arguement go 1 child deeper
return $array["array1"] //if second argument exists ["array2"];
?>
I need this to parse multidimensional arrays independantly , so I can use it on any Multi dimensional array.
Still just guessing at what you're trying to achieve
$this->myArray = array("key1" => array("key2" => array(1,2,3)));
protected function mdparser(){
$result = $this->myArray;
for($i = 0;$i < func_num_args();$i++){
$result = $result[func_get_arg($i)];
}
return $result;
}
$result = this->mdparser('key1', 'key2', 1);
PHP >= 5.6 allows variadics to simplify this:
protected function mdparser(...$args){
$result = $this->myArray;
foreach($args as $arg){
$result = $result[$arg];
}
return $result;
}
Just pass the array to the method when you call it, assuming you are calling it from somewhere where $array is in scope
Also change the array you are building so you have a known, easily processible index i.e. 0.1.2... and not 'array1', 'array2',....
<?php
$array = array( array(), array() );
function mdparser($array){
return $array[count($array)-1];
}
$last_array = mdparser($array);
?>
This should return the last array within the outer array.
Doesnt matter now ive found a way thanks anyways:
function search_array(){
$args = func_get_args();
$arg_num = func_num_args();
for($i = 0;$i < $arg_num;$i++){
$arg = $args[$i];
//foreach arguement go 1 child deeper
$array = $this->array[$arg];
$this->array = $array;
//if second argument exists ["array2"];
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I need to return the array which contains the search string in the range .
Basically i want to search for string with pakistan1 and do not take above that that is it should ignore the array with key 0
second string bangladesh4 it should ignore any other keys below 4
Final return array should be
array(
[2]=>
[3]=>
[4]=>
)
There are two strings which needs to be searched. How I can go about ?
First : pakistan2
Second : bangladesh4
$input_arr= array(
0=>array(india0,srilanka1,pakistan0,banglades0),
1=>array(india1,srilanka1,pakistan1,bangladesh1),
2=>array(india2,srilanka2,pakistan2,bangladesh2),
3=>array(india3,srilanka3,pakistan3,bangladesh3),
4=>array(india 4,srilanka4,pakistan4,bangladesh4),
5=>array(india 5,srilanka5,pakistan5,bangladesh5),
);
I want to return the resulting array as :
$result_arr= array(
2=>array(india2,srilanka2,pakistan2,bangladesh2),
3=>array(india3,srilanka3,pakistan3,bangladesh3),
4=>array(india 4,srilanka4,pakistan4,bangladesh4)
)
EDITED
$first_str = "pakistan2";
$second_str = "bangladesh4";
$arr_output = array();
foreach($input_arr as $key=>$temp_arr)
{
if(in_array($first_str, $temp_arr) || in_array($second_str, $temp_arr) )
{
$arr_output[$key]=$temp_arr;
}
}
Not able to get
array 3
try this
$input_arr= array(
0=>array("india0","srilanka1","pakistan0","banglades0"),
1=>array("india1","srilanka1","pakistan1","bangladesh1"),
2=>array("india2","srilanka2","pakistan2","bangladesh2"),
3=>array("india3","srilanka3","pakistan3","bangladesh3"),
4=>array("india 4","srilanka4","pakistan4","bangladesh4"),
5=>array("india 5","srilanka5","pakistan5","bangladesh5"),
);
$first_str = "pakistan2";
$second_str = "bangladesh4";
$arr_output = array();
foreach($input_arr as $key=>$temp_arr)
{
if(in_array($first_str, $temp_arr) || in_array($second_str, $temp_arr) )
{
$arr_output[$key]=$temp_arr;
}
}
print_r($arr_output);
Try this
$result_arr= array();
for($i=0;$i<sizeof($input_arr);$i++)
{
if(in_array("searchstring",$input_arr[$i]))
if(in_array("searchstring2",$input_arr[$i]))
$result_arr = $input_arr[$i];
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a function that searches through an array of vegetable varieties to see if it matches an ID:
// my function
function findVariety($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, findVariety($subarray, $key, $value));
}
return $results;
}
// function call
$picks = findVariety($veg,id,$sf->spring_choice);
when successful, it returns something like this:
// returned from print_r($picks);
Array ( [0] => Array ( [id] => 2 [variety] => Royal Burgundy (bush) ) )
All I'm missing is how to add the variety to an echo that I'm sending to my page, Ex:
echo '<td height="90px">'.$picks['variety'] .'<br />add plants</td>';
As of now, I have been stuck on this last step! Any help would be amazing...
Your returned array is nested so to access the variety you'd need to do this:
echo $picks[0]['variety']