Not sure why I can't this to work. My json is:
[values] => Array
(
[0] => Array
(
[field] => id1
[value] => 985
)
[1] => Array
(
[field] => id2
[value] => 6395
)
[2] => Array
(
[field] => memo
[value] => abcde
)
I simply want the values of id2
I tried:
foreach ($json['values'] as $values) {
foreach ($json as $key=>$data) {
if ($data['field'] == 'id2') {
$result = $data['value'];
print '<br>value: '.$result;
}
}
}
Thanks. I know this should be relatively simple and I'm sure I've done this correctly before.
there's no need for inner loop, after the first one $values already contain the exact array that you are looking for
foreach ($json['values'] as $values) // $values contain
{
if ($values['field'] == 'id2')
{
$result = $values['value'];
print '<br>value: '.$result;
}
}
foreach ($json['values'] as $values) { //you're looping your first array, puttin each row in a variable $values
foreach ($values as $key=>$data) { //you're looping inside values taking the array index $key and the value inside that index $data
if ($key == 'id2') { //test if $key (index) is = to id2
print '<br>value: '.$value; // print the value inside that index
}
}
}
this is just an explanation, to what is going wrong with your code, but as #Pawel_W there is no need for the second foreach loop you can directly test
if($values['field']=='id2'){ print $values['value'];}
I think you just need to use array_search.
And here is recursive array_search ;
Assuming there might be multiple fields with the same name and you want them all as array, here's an alternative take:
array_filter(array_map(function($item) { return $item['field'] == 'id2' ? $item['value'] : null; }, $json['values']));
If your field names are always unique and you just want a single scalar:
array_reduce($json['values'], function($current, $item) { return $item['field'] == 'id2' ? $item['value'] : $current; });
(note that this one is not ideal since it will walk all the array even if match is found in first element)
And here's a gist with both in this and function form + output.
Related
I'm trying to get two key values and add them both to a foreach. I can't seem to get it to work. Any help will be appreciated.
So I have an array that looks like this:
(
[0] => Array
(
[Code1] => M22
[Code2] => M33
[Code3] => S44
)
[1] => Array
(
[Code1] => E22
[Code2] => E33
[Code3] => E44
)
)
How can I search in the array and get the key and values for
Code2 & Code3 and add both of them to a foraeach?
I can get the Code3 by doing this. This works for the last array element using "array_pop" but can't figure out how to get Code2.
// Filter and get the Code3
$pcodes = array_map('array_pop', $this->dpparent);
foreach ($pcodes as $parent_code) {
echo "\r\n". $parent_code;
}
The simplest way is probably a double for loop:
foreach ($data as $subarray) {
foreach ($subarray as $key => $value) {
if (in_array($key, ['Code2', 'Code3'], true)) {
// Logic here
}
}
}
If you know the name of the keys, then you can use array_column to extract the values:
$code2values = array_column($data, 'Code2');
$code3values = array_column($data, 'Code3');
foreach ($code2values as $key => $code2) {
$code3 = $code3values[$key];
// do something with $code2 and $code3
echo "code2: $code2, code3: $code3\n";
}
Output (for your sample data):
code2: M33, code3: S44
code2: E33, code3: E44
Demo on 3v4l.org
I am attempting to unset a row in a multi-dimensional array based on finding one of the values (the product code)
Here is a slightly simplified structure/content of the array:
Array ([0] => Array ( [item_id] => code1 [item_desc] => first product [item_price] => 5.45 )
[1] => Array ( [item_id] => code2 [item_desc] => second product [item_price] => 9.25 ))
The following works fine except when trying to delelete the first item [0] in the array - so the first item in the basket cannot be deleted.
$pid = 'code2';
$key = array_search($pid, array_column($_SESSION['cart_array'], 'item_id'));
if($key) {
unset($_SESSION['cart_array'][$key]);
sort($_SESSION["cart_array"]);
}
Where the value of $pid = 'code1', $key returns false and the session variable content remains unchanged
I have tried using a foreach loop, which will find the value but I seem unable to get back to the key
foreach ($_SESSION['cart_array'] as $search)
{
if($pid == $search['item_id'])
{
echo key($search); // returns item_id
}
}
Any help much appreciated.
When using the return value of array_search(), this may return 0 for the first item (as you know) and when you test 0 - this is the same as false, you need to check the key to be not equivalent to false...
if($key !== false) {
Use a simpler approach:
$_SESSION['cart_array'] = array_filter($_SESSION['cart_array'], function ($item) use ($pid) {
return $item['item_id'] != $pid;
});
This filters all items out of the array which match $pid.
I think this is what you want.
foreach ($_SESSION['cart_array'] as $key => $search)
{
if($pid == $search['item_id'])
{
echo $key;
}
}
I am using PHP & I have a multi dimensional array which I need to search to see if the value of a "key" exists and if it does then get the value of the "field". Here's my array:
Array
(
[0] => Array
(
[key] => 31
[field] => CONSTRUCTN
[value] => LFD_CONSTRUCTION_2
)
[1] => Array
(
[key] => 32
[field] => COOLING
value] => LFD_COOLING_1
)
)
I want to be able to search the array for the "key" value of 31. If it exists, then I want to be able to extract the corresponding "field" value of "CONSTRUCTN".
I've tried using array_search(31, $myArray) but it does not work...
function searchMultiArray($val, $array) {
foreach ($array as $element) {
if ($element['key'] == $val) {
return $element['field'];
}
}
return null;
}
And then:
searchMultiArray(31, $myArray);
Should return "CONSTRUCTN".
One-line solution using array_column and array_search functions:
$result = array_search(31, array_column($arr, 'key', 'field'));
print_r($result); // CONSTRUCTN
Or with simple foreach loop:
$search_key = 31;
$result = "";
foreach ($arr as $item) { // $arr is your initial array
if ($item['key'] == $search_key) {
$result = $item['field'];
break;
}
}
print_r($result); // CONSTRUCTN
I haven't tested, but I think this should do it.
function searchByKey($value, $Array){
foreach ($Array as $innerArray) {
if ($innerArray['key'] == $value) {
return $innerArray['field'];
}
}
}
Then calling searchByKey(31, $myArray); should return 'CONSTRUCTN'.
One liner solution:
$result = is_numeric($res = array_search(31, array_column($myArray, 'key'))) ? $myArray[$res]["field"] : "";
array_search accepts 2 parameters i.e the value to be search and the array, subsequently I've provided the array which needs searching using array_column which gets that particular column from the array to be searched and is_numeric is used to make sure that valid key is returned so that result can displayed accordingly.
I have an array of values, and i want to insert the values to another array but with an if condition, if the "if" is true I want to skip the iteration.
Code:
$array=array(array(1=>11,2=>22,3=>23,4=>44,5=>55));
$insert=array();
foreach($array as $k1=>$v1)
{
foreach($v1 as $k2=>$v2)
{
if($v2==23)
{
break;
}
}
$insert[]=$v1;
}
final result should look like that
Array
(
[0] => Array
(
[1] => 11
[2] => 22
[3] => 44
[4] => 55
)
)
I tried using: break,return,continue...
Thanks
There are a few ways to do this. You can loop over the outer array and use array_filter on the inner array to remove where the value is 23 like this (IMO preferred; this also uses an array of $dontWant numbers so it is easier to add or change numbers later):
<?php
$array = array(array(1=>11,2=>22,3=>23,4=>44,5=>55));
$insert = array();
//array of numbers you don't want
$dontWant = array(23);
//loop over outer array
foreach($array as $subArray){
//add to $insert a filtered array
//subArray is filtered to remove where value is in $dontWant
$insert[] = array_filter($subArray, function($val) uses ($dontWant) {
//returns true if the value is not in the array of numbers we dont want
return !in_array($val, $dontWant);
});
}
//display final array
echo '<pre>'.print_r($insert,1).'</pre>';
Or you can reference the first key to add to a sub array in $insert like (which is a little more like what your code is trying to do and show that you are not too far off):
<?php
$array = array(array(1=>11,2=>22,3=>23,4=>44,5=>55));
$insert = array();
//loop over outer array
foreach($array as $k1=>$v1){
//add an empty array to $insert
$insert[$k1] = array();
//loop over inner array
foreach($v1 as $k2=>$v2){
//if the inner array value is not 23
if($v2 != 23){
//add to inner array in insert
$insert[$k1][] = $v2;
}
}
}
//display the result
echo '<pre>'.print_r($insert,1).'</pre>';
Both of these methods would produce the same result. IMO using array_filter is the preferred method, but the second method might be a little easier to understand for someone new to programming.
Why don't you just try it like this?
foreach($v1 as $k2=>$v2)
{
if($v2!=23)
{
$insert[]=$v2;
}
}
EDIT:
Explanation: You check with the if($v2!=23) if the value of the variable $v2 is not equal to (that is the != sign) any given number that stands after the inequality operator, and if so, it will insert that value to the array $insert.
I hope it is clear now.
Sorry, I've written $v1 instead of $v2, the code should work now.
To add variants :)
$array=array(array(1=>11,2=>22,3=>23,4=>44,5=>55));
$insert=array();
foreach($array as $a)
{
while (($i = array_search(23, $a)) !== false)
{ unset($a[$i]); sort($a); }
$insert[] = $a;
}
print_r($a);
result:
Array ( [0] => Array ( [0] => 11 [1] => 22 [2] => 44 [3] => 55 ) )
I have an array ($myArray) like this:
print_r(array_values ($myArray));
result: Array (
[0] =>
[1] => Array (
[id] => 1
[name] => ABC
)
[2] => Array (
[id] => 2
[name] => DEF
)
)
I'm trying to get each ID and NAME.. So Im trying this:
foreach ($myArray as $value) {
foreach($value as $result) {
echo $result;
}
}
I'm facing two problems:
I get a PHP WARNING that says: " Invalid argument supplied for foreach() on line 29
This line is: foreach($value as $result) {
I would like to get keys to ID and NAME to place them in correct places. This ways echo "1ABC" and "2DEF"
Any idea? Thanks for helping.
Basically, the error triggered, since the array in your example (index zero in particular) is not an array (most likely an empty string/null ) which is being used inside foreach.
Since one of the elements is not an array, you could just check that if its an array or not using is_array():
foreach($myArray as $values) {
if(is_array($values)) {
echo $values['id'] . ' ' . $values['name'] . '<br/>';
}
}
Alternatively, you could also use array_filter() in this case which in turn removes that empty index zero, so that you could just use that loop that you have. You wouldn't have to check for that empty element.
$myArray = array_filter($myArray);
foreach ($myArray as $value) {
foreach($value as $result) {
echo $result;
}
}
try this,
foreach (array_slice($myArray ,1) as $value) {
foreach($value as $result) {
echo $result;
}
}
the 1st position is empty so omit first position