Error in Array execution in foreach loop : - php

Someone please help me correcting the errors in this code
This was the code where i am trying to find the names of the icecreams in stock
<?php
$flavors = array();
$flavors[]=array("name" => "CD" , "in_stock" => true);
$flavors[]=array("name" => "V" , "in_stock" => true);
$flavors[]=array("name" => "S" , "in_stock" => false);
foreach($flavors as $flavor => $value) {
if($flavor["in_stock"] == true) {
echo $flavor["name"] . "\n";
}
}
?>

You have flat non-associative array, that means you don't need to iterate using $key => $value but just $item.
So in you case the fix is that simple:
https://ideone.com/j7RMAH
...
// foreach ($flavors as $flavor => $value) {
foreach ($flavors as $flavor) {
...

foreach() - foreach will additionally assign the current element's key to the $key variable on each iteration
foreach (array_expression as $key => $value)
statement
Note: You can use any variable it's not necessary to use the variable with name $key
You are using the key for the condition $flavor["in_stock"] and same for the $flavor["name"]. You need to use $value which holding the current iteration array, correct use of foreach for your code is
foreach($flavors as $flavor => $value) {
if($value["in_stock"] == true) {
echo $value["name"] . "\n";
}
}

Why iterate at all? One can just filter an array with a condition:
<?php
$flavors = [];
$flavors[] = ['name' => 'CD', 'in_stock' => true];
$flavors[] = ['name' => 'V', 'in_stock' => true];
$flavors[] = ['name' => 'S', 'in_stock' => false];
$inStock = array_filter($flavors, function (array $flavor) {
return $flavor['in_stock'];
});
print_r($inStock);
$inStockFlavors = array_column($inStock, 'name');
print_r($inStockFlavors);

Related

How to sum column value or multiple values in multi-dimensional array?

How can I add all the columnar values by associative key? Note that key sets are dynamic and some key value is more than one.
Example array :
$myArray = array(
["apple" => 2,"orange" => 1,"lemon" => 4,"grape" => 5],
["apple" => 5,"orange" => 0,"lemon" => 3,"grape" => 2],
["apple" => 3,"orange" => 0,"lemon" => 1,"grape" => 3],
);
With single key value I can sum the column value easily with the code below.
$sumArray = array();
foreach ($myArray as $k => $subArray)
{
foreach ($subArray as $id => $value)
{
if (array_key_exists($id, $sumArray))
{
$sumArray[$id] += $value;
} else {
$sumArray[$id] = $value;
}
}
}
echo json_encode($sumArray);
the result will be like these:
{"apple":10,"orange":1,"lemon":8,"grape":10}
For multiple key values the code above is not working. How to sum column values if key value is more than one?
Example array:
$myArraymulti = array(
["apple" => 2,"orange" => 1,"lemon" => [4, 2],"grape" => 5],
["apple" => 5,"orange" => [0, 2],"lemon" => 3,"grape" => 2],
["apple" => 3,"orange" => 0,"lemon" => 1,"grape" => [3, 8]],
);
Desired result:
{"apple":10,"orange":3,"lemon":10,"grape":18}
Check if the value is an array. If it is, use the sum of the elements instead of the value itself when adding to the associative array.
foreach ($myArray as $k => $subArray)
{
foreach ($subArray as $id => $value)
{
if (is_array($value)) {
$value_to_add = array_sum($value);
} else {
$value_to_add = $value;
}
if (array_key_exists($id, $sumArray))
{
$sumArray[$id] += $value_to_add;
} else {
$sumArray[$id] = $value_to_add;
}
}
}
I suggest you fix your data structure, though. You should just make every value an array, rather than mixing singletons and arrays, so you don't have to use conditionals in all the code that processes the data.
$keys = [];
forEach($myArraymulti as $array){
$keys = array_merge(array_keys($array), $keys);
}
$res = [];
forEach(array_unique($keys) as $key){
forEach($myArraymulti as $array){
if(isset($array[$key])){
$res[$key] = (isset($res[$key]) ? $res[$key] : 0) +
(is_array($array[$key]) ? array_sum($array[$key]) : $array[$key]);
}
}
}
$res = json_encode($res));

create multidimensional json array from a json in php

I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.
Here is my data any code. Thanks in advance
My json data
$val = [
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p1'
},
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p2'
},
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p3'
},
{
'city':'xx',
'zone':'ww',
'person_on_zone':'p1'
},
]
My expectation is
[
{
'city':'xx',
'zone':'yy',
'person_info':{
'person_on_zone':'p1',
'person_on_zone':'p2',
'person_on_zone':'p3',
}
},
{
'city':'xx',
'zone':'ww',
'person_info':{
'person_on_zone':'p1'
}
},
]
Here I tried
foreach ($val as $v) {
$new_array['city'] = $v['city'];
$new_array['zone'] = $v['zone'];
foreach ($val as $v2) {
$new_array['person_info'] = $v['person_on_zone'];
}
}
json_encode($new_array);
Try this, use $map to store key city-zone, then transform to array to get the result
<?php
$val = [
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p1'
],
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p2'
],
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p3'
],
[
'city' => 'xx',
'zone' => 'ww',
'person_on_zone' => 'p1'
]
];
$map = [];
foreach ($val as $v) {
$key = $v['city'] . $v['zone'];
if (!isset($map[$key])) {
$map[$key] = [
'city' => $v['city'],
'zone' => $v['zone'],
'person_info' => []
];
}
$map[$key]['person_info'][] = $v['person_on_zone'];
}
print_r(array_values($map));
Correct Code
foreach ($val as $v){
$new_array['city'] = $v['city'];
$new_array['zone'] = $v['zone'];
foreach ($val as $v2){
$new_array['person_info'] = $v2['person_on_zone'];
}
}
json_encode($new_array);
try this:
first decode json array then use foreach loop with key
$val = json_decode($val);
foreach ($val as $v){
$new_array['city'] = $v->city;
$new_array['zone'] = $v->zone;
foreach ($val as $key=>$v2){
$new_array[$key]['person_info'] = $v->person_on_zone;
}
}
print_r($new_array);
I think you make a mistake around composing the json. I tried with your code and i found following is the correct way to do.. Remember single quote(') is not valid in json string that is being used to define key value pair in php
// I think your code has json string and i convert it into array of objects(stdClass)
// and if your code has array then keep you code intact but need to change the notation of
// objects to associative array.
// first thing first decode json string
$values = json_decode('[
{ "city":"xx",
"zone":"yy",
"person_on_zone":"p1"
},
{
"city":"xx",
"zone":"yy",
"person_on_zone":"p2"
},
{
"city":"xx",
"zone":"yy",
"person_on_zone":"p3"
},
{
"city":"xx",
"zone":"ww",
"person_on_zone":"p1"
}]');
// Now declare new values as array
$new_values = [];
// walk through each object
foreach ($values as $v){
// $v becomes an object of stdClass here
// $data is a temporary array
$data['city'] = $v->city;
$data['zone'] = $v->zone;
$data['person_info'] = [];
foreach ($values as $v2){
if(!in_array($data['person_info'],['person_on_zone' => $v2->person_on_zone]))
{
// compare if zones are same or not
if($v->zone == $v2->zone)
{
// push to the array instead of assiging
array_push($data['person_info'], ['person_on_zone' => $v2->person_on_zone]);
}
}
}
// make array unique
$data['person_info'] = array_map("unserialize", array_unique(array_map("serialize", $data['person_info'])));
array_push($new_values, $data);
}
// make array unique in mutidimensional array
$new_values = array_map("unserialize", array_unique(array_map("serialize", $new_values)));
echo '<pre>';
print_r($new_values);
echo '</pre>';
One simple foreach would do,
$result = [];
foreach ($arr as $key => $value) {
//created unique combination of city and zone as key
$result[$value['city'] . $value['zone']]['city'] = $value['city'];
$result[$value['city'] . $value['zone']]['zone'] = $value['zone'];
$result[$value['city'] . $value['zone']]['person_info'][] = ['person_on_zone' => $value['person_on_zone']];
}
echo json_encode(array_values($result));die;
array_values — Return all the values of an array
Working demo.

how to assign id based on array values

I am learning php please help.
I am storing values in an array and then I am trying to get the id of another array checking the value in array like this:
$arr_folders = ['one', 'two', 'whatever'];
$id_one = '';
$id_two = '';
$id_whatever = '';
foreach ($tree as $key => $value) {
if($value['name'] == 'one'){//how to check dynamically?
$id_one = $value['id'];
}
if($value['name'] == 'two'){//how to check dynamically?
$id_two = $value['id'];
}
if($value['name'] == 'whatever'){//how to check dynamically?
$id_whatever = $value['id'];
}
}
echo $id_whatever;
How can I check the arrays values dynamically. I mean I want to check if the value exist in array then assign their id.
You need to use in_array to check whether the element is exist or not in another array, and if found you can create dynamic variable based on $value['name'] containing $value['id'] as required.
$tree = [
['id' => 1, 'name' => 'one'],
['id' => 2, 'name' => 'two'],
['id' => 3, 'name' => 'three']
];
$arr_folders = ['one', 'two', 'whatever'];
foreach ($tree as $key => $value) {
if (in_array($value['name'], $arr_folders)) {
${'id_'.$value['name']} = $value['id'];
}
}
echo $id_one;
Working Example: https://eval.in/596034
Note: make sure $value['name'] doesn't contain spaces or any other characters which aren't allowed to declare variable names.
Try using array search
For example:
<?php
$arr_folders = ['one', 'two', 'whatever'];
foreach ($tree as $key => $value) {
if (($key = array_search($arr_folders, $value)) !== false) {
return $arr_folders[$key];
}
}
echo $id_whatever;
If I understand the question, you're asking how you can check for the contents of one array (in this case, [one, two, whatever]) in the middle of looping through the other array without hardcoding it. If that's the case, I might try something like this:
$arr_folders = ['one', 'two', 'whatever'];
$id_folders = ['', '', '']
foreach ($tree as $key => $value) {
foreach ($arr_folders as $fkey => $fvalue) { // f for folder, in this case
if($value['name'] == $fvalue){
$id_folders[$fkey] = $value['id'];
}
}
}
echo $id_folders[2];
There may be other more elegant or time-effficient solutions, but I think this captures the dynamic nature you're looking for while mirroring the actual process of the previous code.
here is sample code :
<?php
$arr_folders = ['one', 'two', 'whatever'];
$tree= Array(Array('id' => 1,'name' => 'one'),
Array('id' => 2,'name' => 'large'),
Array('id' => 3,'name' => 'thumb'),
Array('id' => 4,'name' => 'two'),
Array('id' => 5,'name' => 'large'),
Array('id' => 6,'name' => 'thumb')
);
foreach ($tree as $key => $value) {
if(in_array($value['name'],$arr_folders)){
$searchedIds[] = $value['id'];
}
}
print_r($searchedIds);
?>

Search in a multidimensional assoc array

I have an array, looking like this:
[lund] => Array
(
[69] => foo
)
[berlin] => Array
(
[138] => foox2
)
[tokyo] => Array
(
[180] => foox2
[109] => Big entrance
[73] => foo
)
The thing is that there were duplicate keys, so I re-arranged them so I can search more specifically, I thought.
Previously I could just
$key = array_search('foo', $array);
to get the key but now I don't know how.
Question: I need key for value foo, from tokyo. How do I do that?
You can get all keys and value of foo by using this:
foreach ($array as $key => $value) {
$newArr[$key] = array_search('foo', $value);
}
print_r(array_filter($newArr));
Result is:
Array
(
[lund] => 69
[tokyo] => 109
)
If you don't mind about the hard code than you can use this:
array_search('foo', $array['tokyo']);
It just a simple example, you can modify it as per your requirement.
Try this
$a = array(
"land"=> array("69"=>"foo"),
"land1"=> array("138"=>"foo1"),
"land2"=> array('180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'),
);
//print_r($a);
$reply = search_in_array($a, "foo");
print_r($reply);
function search_in_array($a, $search)
{
$result = array();
foreach($a as $key1 => $array ) {
foreach($array as $k => $value) {
if($value == "$search") {
array_push($result,"{$key1}=>{$k}");
breck;
}
}
}
return $result;
}
This function will return the key or null if the search value is not found.
function search($searchKey, $searchValue, $searchArr)
{
foreach ($searchArr as $key => $value) {
if ($key == $searchKey && in_array($searchValue, $value)) {
$results = array_search($searchValue, $value);
}
}
return isset($results) ? $results : null;
}
// var_dump(search('tokyo', 'foo', $array));
Since Question: I need key for value foo, from tokyo. How do i do that?
$key = array_search('foo', $array['tokyo']);
As a function:
function getKey($keyword, $city, $array) {
return array_search($keyword, $array[$city]);
}
// PS. Might be a good idea to wrap this array in an object and make getKey an object method.
If you want to get all cities (for example to loop through them):
$cities = array_keys($array);
I created solution using array iterator. Have a look on below solution:
$array = array(
'lund' => array
(
'69' => 'foo'
),
'berlin' => array
(
'138' => 'foox2'
),
'tokyo' => array
(
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
)
);
$main_key = 'tokyo'; //key of array
$search_value = 'foo'; //value which need to be search
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
$keys = array();
if ($value == $search_value) {
$keys[] = $key;
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$keys[] = $iterator->getSubIterator($i)->key();
}
$key_paths = array_reverse($keys);
if(in_array($main_key, $key_paths) !== false) {
echo "'{$key}' have '{$value}' value which traverse path is: " . implode(' -> ', $key_paths) . '<br>';
}
}
}
you can change value of $main_key and $serch_value according to your parameter. hope this will help you.
<?php
$lund = [
'69' => 'foo'
];
$berlin = [
'138' => 'foox2'
];
$tokyo = [
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
];
$array = [
$lund,
$berlin,
$tokyo
];
echo $array[2]['180']; // outputs 'foox2' from $tokyo array
?>
If you want to get key by specific key and value then your code should be:
function search_array($array, $key, $value)
{
if(is_array($array[$key])) {
return array_search($value, $array[$key]);
}
}
echo search_array($arr, 'tokyo', 'foo');
try this:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'On');
$array=array("lund" => array
(
69 => "foo"
),
"berlin" => array
(
138 => "foox2"
),
"tokyo" => array
(
180 => "foox2",
109 => "Big entrance",
73 => "foo"
));
function search($array, $arrkey1, $arrvalue2){
foreach($array as $arrkey=>$arrvalue){
if($arrkey == $arrkey1){
foreach($arrvalue as $arrkey=>$arrvalue){
if(preg_match("/$arrvalue/i",$arrvalue2))
return $arrkey;
}
}
}
}
$result=search($array, "tokyo", "foo"); //$array=array; tokyo="inside array to check"; foo="value" to check
echo $result;
You need to loop through array, since its 2 dimensional in this case. And then find corresponding value.
foreach($arr as $key1 => $key2 ) {
foreach($key2 as $k => $value) {
if($value == "foo") {
echo "{$k} => {$value}";
}
}
}
This example match key with $value, but you can do match with $k also, which in this case is $key2.

Add elements to all empty keys of an array

I use the following code to fill all empty keys in sub-arrays with ``:
$array = array(
'note' => array('test', 'test1'),
'year' => array('2011','2010', '2012'),
'type' => array('conference', 'journal', 'conference'),
);
foreach ($array['type'] as $k => $v) {
foreach($array as $element => $a) {
$iterator = $array[$element];
if(!isset($iterator[$k])){
$iterator[$key] = '';
}
}
}
print_r($array);
The problem is that it is not actually changing the elements in $array but in temporary variable $iterator.
I know that this is a simple question but I would like to find out the best and fastest solution.
You don't need the $iterator variable, you can do just:
foreach ($array['type'] as $k => $v) {
foreach($array as $element => $a) {
if(!isset($array[$element][$k])){
$array[$element][$key] = '';
}
}
}
I would also recommending switching the inner and outer loops, so it's more readable and more efficient.
foreach($array as $element => $a) {
foreach ($array['type'] as $k => $v) {
if(!isset($array[$element][$k])){
$array[$element][$key] = '';
}
}
}
Looks like you have some typos. $key in the middle of the loops is never defined.
$a should be the same value as $iterator[$k], so no need to set it.
Try this.
$array = array(
'note' => array('test', 'test1'),
'year' => array('2011','2010', '2012'),
'type' => array('conference', 'journal', 'conference'),
);
foreach ($array as $k => $v) {
foreach($k as $element => $a) {
if(!isset($a)){
$array[$element] = '';
}
}
}

Categories