PHP - Nested Foreach Change Original Array Values [duplicate] - php

This question already has answers here:
How to modify an array's values by a foreach loop?
(2 answers)
Closed 4 months ago.
I have a multidimensional associative array and im using two foreach to iterate them, i need to change a value from the original array, here a representation of my code and what ive tried:
$array = [
['id' => 1, 'customers' => [['customerName' => 'Daniel', 'age' => 20, 'isYoung' => false], ['customerName' => 'Patrick', 'age' => 56, 'isYoung' => false]]],
['id' => 4, 'customers' => [['customerName' => 'Paul', 'age' => 41, 'isYoung' => false]]]
];
foreach($array as $key => $value) {
foreach($value['customers'] as $sKey => $sValue {
if($sValue['age'] < 35) {
$array[$key]['customers'][$sKey]['isYoung'] = true; //Doesnt Work
$value['customers'][$sKey]['isYoung'] = true; //Doesnt Work
}
}
}
Any leads?

The first assignment works for me. But you can simplify it by using reference variables for the iteration variables.
foreach($array as &$value) {
foreach($value['customers'] as &$sValue) {
if($sValue['age'] < 35) {
$sValue['isYoung'] = true;
}
}
}

Related

Flatten a multi dimensional array inside a multi dimensional array but retain keys? [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 3 years ago.
$arr = [
'name' => 'John',
'access' => '1',
'address' => [
'line_1' => '10',
'line_2' => 'example street',
],
]
How can I flatten this example array (or turn it into a collection) without losing keys, I've tried to use collect and flatten but this loses the keys.
I'm expecting this:
$arr = [
'name' => 'John',
'access' => '1',
'line_1' => '10',
'line_2' => 'example street',
]
You can try like this by using core iterator functions,
$temp = [];
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($it as $k => $v) {
$temp[$k] = $v;
}
print_r($temp);
RecursiveIteratorIterator - Can be used to iterate through recursive iterators.
RecursiveArrayIterator - This iterator allows to unset and modify values and keys while iterating over Arrays and Objects in the same way as the ArrayIterator. Additionally it is possible to iterate over the current iterator entry.
Output
Array
(
[name] => John
[access] => 1
[line_1] => 10
[line_2] => example street
)
Demo.
I think #Rahul Meshram's solution is better, but you can try this one, too.
Try
<?php
$arr = [
'name' => 'John',
'access' => '1',
'address' => [
'line_1' => '10',
'line_2' => 'example street',
],
];
$newArray = [];
foreach ($arr as $k1 => $v1){
if(is_array($v1) && count($v1) > 0){
foreach ($v1 as $k2 => $v2){
$newArray[$k2] = $v2 ;
}
}else {
$newArray[$k1] = $v1 ;
}
}
print_r($newArray);

Laravel : How to count specific array values

I have been trubling with session array part...as my session array have 3 different value coming from database ...easy ...medium ...hard....how i count these specificly?
Session::push('getscoresession',$getscore);
Session::push('level',$level);
$getsession = [ 'qid' => $getidvalue, 'answer' => $getanswervalue];
Session::push('answer', $getsession);
$score = array_count_values(Session::get("level"));
return view('score',compact('score'));
getting this error message: array_count_values(): Can only count STRING and INTEGER values!`
Here is your solution:
$array = [
0 => 'easy',
1 => 'easy',
2 => 'easy',
3 => 'medium',
4 => 'medium',
5 => 'medium',
6 => 'hard',
7 => 'hard',
8 => 'hard',
9 => 'hard',
10 => 'hard'
];
echo "<pre>";
print_r($array);
var_dump(array_count_values($array));
Another solution:
// This is static
$stats = [
'easy' => 0,
'medium' => 0,
'hard' => 0,
];
// Alternatively dynamic way:
$a = array_flip(array_unique($array));
$b = array_fill_keys(array_keys($a), 0);
foreach($array as $value) {
$stats[$value]++; // Static Way
$b[$value]++; // Dynamic way
}
echo "<pre>";
print_r($stats);
print_r($b);
exit;
You can use http://www.writephponline.com/ to execute above code.
In your blad file:
Use foreach
#foreach($data as $key => $value)
{{ $key .'-'. $value }}
#endforeach
Let me know if you still have any query.
It's may be because you may have null values in your array.
Possible solutions :
Either remove null values from your array.
Or use array_filter.
See this example:
https://repl.it/repls/TameFarLine

PHP Loop Multidimensional Associative Array [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 3 months ago.
I have this output:
I don't have any idea how can I make my array look like this:
$array[
0 => [
'item_id' => 6,
'price' => "2311.00",
'qty' => 12,
'discount' => 0
],
1 => [
'item_id' => 7,
'price' => "1231.00",
'qty' => 1,
'discount' => 12
],
2 => [
'item_id' => 8,
'price' => "123896.00",
'qty' => 0,
'discount' => 24
]
]
I have started the loop but I don't really know how to get that kind of structure.
foreach( $array as $wishlist ){
foreach( $wishlist as $k => $v ){
}
}
You can iterate the outer and inner arrays to build your data like so, this allows you to add further keys to the array later - but does depend on your inner array keys being contiguous
$wishlist = [];
foreach ($array as $outerKey => $outerValue) {
foreach ($outerValue as $innerKey => $innerValue) {
$wishlist[$innerKey][$outerKey] = $innerValue;
}
}
Your loop should look like this:
foreach( $array as $item => $wishlist ){
foreach( $wishlist as $k => $v ){
$new_array[$k][$item] = $v;
}
}
You should have to use for loop.
for($i=0;$i<count(youarray['item_id']);$i++) {
$wishlist[$i]['item_id'] = youarray['item_id'][$i];
$wishlist[$i]['price'] = youarray['price'][$i];
$wishlist[$i]['qty'] = youarray['qty'][$i];
$wishlist[$i]['discount'] = youarray['discount'][$i];
}
or user foreach like this
foreach(youarray['item_id'] as $key=>$val) {
$wishlist[$key]['item_id'] = $val;
$wishlist[$key]['price'] = youarray['price'][$key];
$wishlist[$key]['qty'] = youarray['qty'][$key];
$wishlist[$key]['discount'] = youarray['discount'][$key];
}

How To Foreach Array in PHP [duplicate]

This question already has answers here:
PHP foreach with Nested Array?
(6 answers)
Closed 7 years ago.
I have a array like this. I want to loop over the array, but do not know how to handle the internal arrays. Can anyone help me?
$a = array(
0 => array(
'B' => array(
'company' => 'ZZZZZZ'
),
'User' => array(
'company' => 'ABC'
),
0 => array(
'jumlah' => null,
'jumbuy' => '98990',
'admin' => '2010'
)
)
);
If you want to use foreach on this array do like this.
foreach($a as $key=>$value)
{
print_r($value);
}
You can also use nested foreach.
You can use a recursive function (but these can spiral out of control).
function print_array($array) {
foreach($array as $key => $value) {
echo "{$key} is: ";
if (is_array($value)) {
echo "an array.\n"
print_array($value);
} else {
echo "{$value}.\n";
}
echo "\n";
}

Get path and value of all elements in nested associative array

Consider an associative array of arbitrary form and nesting depth, for example:
$someVar = array(
'name' => 'Dotan',
'age' => 35,
'children' => array(
0 => array(
'name' => 'Meirav',
'age' => 6,
),
1 => array(
'name' => 'Maayan',
'age' => 4,
)
),
'dogs' => array('Gili', 'Gipsy')
);
I would like to convert this to an associative array of paths and values:
$someVar = array(
'name' => 'Dotan',
'age' => 35,
'children/0/name' => 'Meirav',
'children/0/age' => 6,
'children/1/name' => 'Maayan',
'children/1/age' => 4,
'dogs/0' => 'Gili',
'dogs/1' => 'Gipsy'
);
I began writing a recursive function which for array elements would recurse and for non-array elements (int, floats, bools, and strings) return an array $return['path'] and $return['value']. This got sloppy quick! Is there a better way to do this in PHP? I would assume that callables and objects would not be passed in the array, though any solution which deals with that possibility would be best. Also, I am assuming that the input array would not have the / character in an element name, but accounting for that might be prudent! Note that the input array could be nested as deep as 8 or more levels deep!
Recursion is really the only way you'll be able to handle this, but here's a simple version to start with:
function nested_values($array, $path=""){
$output = array();
foreach($array as $key => $value) {
if(is_array($value)) {
$output = array_merge($output, nested_values($value, (!empty($path)) ? $path.$key."/" : $key."/"));
}
else $output[$path.$key] = $value;
}
return $output;
}
function getRecursive($path, $node) {
if (is_array($node)) {
$ret = '';
foreach($node as $key => $val)
$ret .= getRecursive($path.'.'.$key, $val);
return $ret;
}
return $path.' => '.$node."\n";
}
$r = getRecursive('', $someVar);
print_r($r);
All yours to place it in an array.

Categories