Match values in a multidemsional array - php

I would like to search an array for one value in a key and return the content from another key in the same array.
Like this:
$cars = array
(
array("brand" => "Volvo","color" => 22),
array("brand" => "BMW","color" => 15),
array("brand" => "Saab","color" => 5),
array("brand" => "Land Rover","color" => 17)
);
// Not working, just to clarify my intention
if($cars['brand'] == 'BMW') {echo $cars['color'];}
In this example, 15 should be echoed.
How can this be accomplished?

This should do it:
foreach($cars as $car) {
if($car['brand'] == 'BMW') {
echo $car['color'];
}
}

You need to create a loop that goes through each possible value. Often, you'd just use a for loop.
for($i = 0; $i < count($cars); $i++) {
if($cars[$i]['brand'] == "BMW")
echo $cars[$i]['color'];
}
However, using a foreach loop is also an option, and it looks neater.
foreach($cars as $v) {
if($v['brand'] == "BMW")
echo $v['color'];
}
See the array, for loop and foreach loop documentation for more information
Arrays
For loop
Foreach loop

You can use the array_filter function in PHP. See this page from the PHP docs and the given example.

Related

Associate array value from foreach with key/value in another array

Say you have the array .
$arr = array('foo' => 'bar, 'wang' => 'chung', 'ying' => 'yang');
Now I want to loop through another array (var = $terms) to get values using foreach. If the value is any of the keys listed in $arr, I want to replace it with the value listed in $arr.
I've tried this ...
foreach($terms as $term => $arr) {
echo $term[$arr];
}
This doesn't work ... and I'm pretty stumped beyond that point. Reading through the manual on foreach ... I felt like this was on the right path - but think I'm needing a nudge in another direction.
Thoughts?
You can use array_key_exists() function for verifying whether key exists in another array or not If found then replace that with existing once. You can refer below answer,
$arr = array('foo' => 'bar', 'wang' => 'chung', 'ying' => 'yang');
$res = [];
foreach($terms as $term => $arr1) {
if( array_key_exists( $term, $arr ) ) {
$res[$term] = $arr[$term];
} else {
$res[$term] = $arr1;
}
}
echo '<pre>'; print_r($res);
I hope this will resolve your problem.

PHP assoiative Array with almost Similar Keys

I have an associative array
array(
'item_name1' => 'PCC',
'item_name2' => 'ext',
'item_number1' => '060716113223-13555',
'item_number2' => '49101220160607-25222)',
)
What i Want to do is catch all the array keys where the key name has similarities
for example
i want to echo out item_name (it should get both item_name1 & item_name2) but i require it in a loop (foreach/for) so that i can send within the loop the details to my database for each set of values
Thanks For the help
Use the funtion array_keys
$allKeys = array_keys($yourArray);
$amountKeys = count($allKeys);
Unless you do not provide more code this will give you all the keys of $yourArray
Reference - array_keys
To get all the similar keys you can use this function similar-text()
Since I do not know how "similar" a key can be I would suggest you to test out different values and find a degree that matches your expectations.
Your data model seems to use numeric suffixes as a replacement for arrays so I'll assume that key name has similarities is an overestimated problem statement and you merely want to fix that.
The obvious tool is regular expressions:
$original_data = array(
'item_name1' => 'PCC',
'item_name2' => 'ext',
'item_number1' => '060716113223-13555',
'item_number2' => '49101220160607-25222)',
);
$redacted_data = array();
foreach ($original_data as $key => $row) {
if (preg_match('/^(.+)(\d+)$/u', $key, $matches)) {
$redacted_data[$matches[1]][$matches[2]] = $row;
} else {
$redacted_data[$key][] = $row;
}
}
var_dump($redacted_data);
It should be easy to tweak for your exact needs.
I can't figure out what the i require it in a loop (foreach/for) requirement means but you can loop the resulting array as any other array:
foreach ($redacted_data as $k => $v) {
foreach ($v as $kk => $vv) {
printf("(%s,%s) = %s\n", $k, $kk, $vv);
}
}
<?php
$items=[];
$itemsNumbers=[];
foreach($itemarr as $key=> $val)
{
$itempos = strpos("item_name", $key);
if ($pos !== false)
$items[]=$val;
$numberpos = strpos("item_number", $key);
if ($numberpos !== false)
$itemsNumbers[]=$val;
}
?>
Note: here $itemarr is your input array
$items you will get list of item names and $itemsNumbers you will get list of itemsNumbers

get value of array of arrays in php

So, let's assume I am not using php 5.4 because I tried
$results[0][0]
and it did not work. My array $results is an array of arrays and I want to return the first value of the first array. How would I do this without doing the above, because it doesn't work.
Let assume that your array looks like this
$results = array(
'k1'=>array(
'k1.1'=>'v1.1',
'k1.2'=>'v1.2',
'k1.3'=>'v1.3',
),
'k2'=>array(
'k2.1'=>'v2.1',
'k2.2'=>'v2.2',
'k2.3'=>'v2.3',
),
);
Then if you need to get first value of the first array this should help
$results[key($results)][key($results[key($results)])];
Looks weird :)
You can use foreach function
foreach($result as $resk => $resv ){
$i = 1;
foreach($resv as $rk => $rv ){
if($i == 1){
echo $rv;
}
$i++;
}
}

php - Find array for which a key have a given value

I have an array of dictionnaries like:
$arr = array(
array(
'id' => '1',
'name' => 'machin',
),
array(
'id' => '2',
'name' => 'chouette',
),
);
How can I find the name of the array containing the id 2 (chouette) ?
Am I forced to reindex the array ?
Thank you all, aparently I'm forced to loop through the array (what I wanted to avoid), I thought that it were some lookup fonctions like Python. So I think I'll reindex with id.
Just find the index of array that contains the id you want to find.
SO has enough questions and answers on this topic available.
Assuming you have a big array with lots of data in your real application, it might be too slow (for your taste). In this case, you indeed need to modify the structure of your arrays, so you can look it up faster, e.g. by using the id as an index for the name (if you are only interested in the name).
As a for loop would be the best way to do this, I would suggest changing you array so that the id is the arrays index. For example:
$arr = array(
1 => 'machin',
2 => 'chouette',
);
This way you could just get the name for calling $arr[2]. No looping and keeping your program running in linear time.
$name;
foreach ($arr as $value){
if ( $value['id'] == 2 ){
$name = $value['name'];
break;
}
}
I would say that it might be very helpful to reindex the information. If the ID is unique try something like this:
$newarr = array();
for($i = 0;$i < count($arr);$i++){ $newarr[$arr[$i]['id']] = $arr[$i]['name']; }
The result would be:
$newarr = array('1'=>'machin','2'=>'chouette');
Then you can go trough the array with "foreach" like this:
foreach($newarr as $key => $value){
if($value == "machin"){
return $key;
}
}
But of course the same would work with your old array:
foreach($arr as $item){
if($item['name'] == "machin"){
return $item['id'];
}
}
It depends on what you are planning to do with the array ;-)
array_key_exist() is the function to check for keys. foreach will help you get down in the multidimensional array. This function will help you get the name element of an array and let you specify a different id value.
function findKey($bigArray, $idxVal) {
foreach($bigArray as $array) {
if(array_key_exists('id', $array) && $array['id'] == $idxVal) {
return $array['name'];
}
}
return false;
}
//Supply your array for $arr
print(findKey($arr, '2')); //"chouette"
It's a bit crude, but this would get you the name...
$name = false;
foreach($arr as $v) {
if($v['id'] == '2') {
$name = $v['name'];
break;
}
}
echo $name;
So no, you are not forced to reindex the array, but it would make things easier.

php How to access array inside array

I have an array which is of the following form in PHP-
Array(
0 =>
array (
0 => 'var1=\'some var1\'',
1 => 'var2=\'some_var2\'',
2 => 'var3=\'some_var3\'',
))
and I want it to appear as-
array (
0 => 'var1=\'some var1\'',
1 => 'var2=\'some_var2\'',
2 => 'var3=\'some_var3\'',
)
So how to do it?
Have you tried...
$inner_array = $outer_array[0];
var_dump($inner_array);
...?
Read here in the manual about more details to arrays in php.
Multidimensional arrays generally work as shown below
$shop = array( array("rose", 1.25 , 15),
array("daisy", 0.75 , 25),
array("orchid", 1.15 , 7)
);
echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2];
The syntax of foreach construct is as follow:
foreach ($array_expression as $value) {
statement
}
foreach ($array_expression as $key => $value) {
statement
}
The first form loops over the array given by $array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one so that on the next loop, the next element is accessed.
The second form does the same thing, except that the current element’s key will be assigned to the variable $key on each loop.
The foreach syntax above is also similar to the following while construct:
while (list(, $value) = each($array_expression)) {
statement
}
while (list($key, $value) = each($array_expression)) {
statement
}
Even for loop can be used to process and loop through all elements of arrays with the following syntax:
$count = sizeof($arr_expression);
for ($i = 0; $i < $count; $i++) {
$value = $arr_express[$i];
statement
}
for ($i = 0, $item = ''; false != ($value = $arr_expression[$i]); $i++) {
statement
}
Nested loop of “foreach” can also be used to access multidimensional arrays. Here’s an example array and the way to access its value data. For example:
foreach ($array_expression as $arr_value) {
foreach ($array_value as $value) {
statement
}
}
Here’s an example code to access an array:
$contents = array(
"website_1" => array("name" => "StackOverFlow",
"url" => "http://www.stackoverflow.com",
"favorite" => "yes"),
"website_2" => array("name" => "Tip and Trick",
"url" => "http://www.tipandtrick.net",
"favorite" => "yes")
);
To retrieve the data, programmers can specify the keys that lead to the value directly with the following syntax, which will print the “My Digital Life”.
echo $contents['website_1']['name'];
However, the syntax above becomes unpractical when dealing with large arrays, or when the name of the keys and values changed dynamically. In this case, the “foreach” function can be used to access an array recursively.
foreach ($contests as $key => $list) {
echo "Website No.: " . $key . "\n";
echo "Name: " . $list['name'] . "\n";
echo "URL: " . $list['url'] . "\n";
}
The output will be:
Website No.: website_1
Name: StackOverFlow
URL: http://www.stackoverflow.com/
Website No.: website_2
Name: Tip and Trick
URL: http://www.tipandtrick.net/

Categories