PHP foreach with multidimensional array not printing all values - php

I have a very simple multidimensional array and some PHP code. The code should print the p_id values, but it does not do it. Do I really have to add one foreach more or is there other ways?
And here is the array:
Array (
[2764] => Array (
[status] => 0
[0] => Array (
[p_id] => 2895
)
[1] => Array (
[p_id] => 1468
)
)
[5974] => Array (
[status] => 0
[0] => Array (
[p_id] => 145
)
[1] => Array (
[p_id] => 756
)
)
)
Here is my PHP code:
foreach($arr as $innerArray)
foreach($innerArray as $key => $value)
echo $key . "=>" . $value . "<br>";
It prints:
status=>0
0=>Array
1=>Array
status=>0
0=>Array
1=>Array

foreach($arr as $a => $a_value)
{
echo $a . '<br>';
foreach($a_value as $av_arr => $av)
{
if(!is_array($av))
{
echo $av_arr . '=>' . $av . '<br>';
}
else
{
foreach($av as $inner_av => $inner_av_val)
{
echo $inner_av . '=>' . $inner_av_val . '<br>';
}
}
}
}

This simple call to array_walk_recursive() produces the output requested in the question:
array_walk_recursive(
$arr,
function ($value, $key) {
echo $key . "=>" . $value . "<br>";
}
);
But it doesn't make much sense as the output mixes the values of status with the values of p_id.
I would go for a more structured display using the original code with a little more meaning for the names of the variables:
foreach ($arr as $catId => $catInfo) {
// Category ID and details; use other names if I'm wrong
printf("Category: %d (status: %s)\n", $catId, $catInfo['status'] ? 'active' : 'inactive');
foreach ($catInfo as $key => $value) {
if ($key == 'status') {
// Ignore the status; it was already displayed
continue;
}
foreach ($value as $prodInfo) {
printf(" Product ID: %d\n", $prodInfo['p_id']);
}
}
}
The structure of the input array tells me you should first fix the code that generates it. It should group all the products (the values that are now indexed by numeric keys) into a single array. It should look like this:
$input = array(
'2764' => array(
'status' => 0,
'products' => array(
2895 => array(
'p_id' => 2895,
'name' => 'product #1',
// more product details here, if needd
),
1468 => array(
'p_id' => 1468,
'name' => 'product #2',
),
// more products here
),
// more categories here
),
Then the code that prints it will look like this:
foreach ($arr as $catId => $catInfo) {
// Category ID and details; use other names if I'm wrong
printf("Category: %d (status: %s)\n", $catId, $catInfo['status'] ? 'active' : 'inactive');
foreach ($catInfo['products'] as $prodInfo) {
printf(" %s (ID: %d)\n", $prodInfo['name'], $prodInfo['p_id']);
// etc.
}
}

Use a recursive function:
function printIds($arr) {
foreach ($arr as $key => $val) {
if (is_array($val) && array_key_exists("p_id", $val)) {
echo $val["p_id"]."\n";
} elseif(is_array($val)) {
printIds($val);
}
}
}
Working example:
$arr = [
2764 => [
'status' => 0,
['p_id' => 100],
],
4544 => [
'status' => 0,
['p_id' => 100],
],
['p_id' => 100],
];
function printIds($arr) {
foreach ($arr as $key => $val) {
if (is_array($val) && array_key_exists("p_id", $val)) {
echo $val["p_id"]"\n";
} elseif(is_array($val)) {
printIds($val);
}
}
}
printIds($arr);
The function loops all entries of a given array and echo's them out, if they contain an array with a key named "p_id". If it does find a nested array, then it does loop also all child arrays.

Related

Group 2d array by column value and concatenate values within each group

I have a simple php array for location postcode and their name. I want compress 'code' by 'name'. This code from WooCommerce database zones.
$new_arr = [
[
'name' => 'Jambi Selatan',
'code' => '36139',
'code_name' => '36139 - Jambi Selatan'
],
[
'name' => 'Jambi Selatan',
'code' => '36137',
'code_name' => '36137 - Jambi Selatan'
],
[
'name' => 'Bagan Pete',
'code' => '36129',
'code_name' => '36129 - Bagan Pete'
],
[
'name' => 'Bagan Pete',
'code' => '36127',
'code_name' => '36127 - Bagan Pete'
]
];
I want get final result combined by 'name' and 'code' like this: i try array_unique method but not working.
Array (
[0] => Array
(
[name] => Jambi Selatan
[code] => 36139, 36137
[code_name] => 36139, 36139 - Jambi Selatan
)
[1] => Array
(
[name] => Bagan Pete
[code] => 36127, 36129
[code_name] => 36127, 36129 - Bagan Pete
)
)
I try this method, but not fix at 'code_name'
$out = array();
foreach ($new_arr as $key => $value){
if (array_key_exists($value['name'], $out)){
$out[$value['name']]['code'] .= ', '.$value['code'];
} else {
$out[$value['name']] = array(
'name' => $value['name'],
'code' => $value['code'],
'code_name' => $value['code'] . ' - ' . $value['name']
);
}
}
$out = array_values($out);
print_r($out);
You have to check duplicate name by in_array and update exist array value .If not exist insert that value to $out array .
$out = array();
foreach($new_arr as $k=>$v) {
//empty array state
if(count($out) == 0) {
$out[] = $v;
continue;
}
foreach ($out as $key => $value) {
if(in_array($v["name"],$value)) {
$out[$key]["code"] .= ",".$v["code"];
//for the code_name output as OP described
$nn = explode("-", $value["code_name"]);
$l = count($nn) - 1;
unset($nn[$l]);
$out[$key]["code_name"] = implode($nn).",".$v["code_name"];
break;
} else {
if((count($out)-1) == $key) {
$out[] = $v;
}
}
}
}
var_dump($out);
For someone have problem like me, this method for fix it:
$out = array();
foreach ($new_arr as $key => $value){
if (array_key_exists($value['name'], $out)){
$out[$value['name']]['code'] .= ', '.$value['code'];
$out[$value['name']]['code_name'] .= ', '.$value['code'] . ' - ' . $value['name'];
} else {
$out[$value['name']] = array(
'name' => $value['name'],
'code' => $value['code'],
'code_name' => $value['code']
);
}
}
$out = array_values($out);
print_r($out);
Final result;
Array
(
[0] => Array
(
[name] => Jambi Selatan
[code] => 36139, 36137
[code_name] => 36139, 36137 - Jambi Selatan
)
[1] => Array
(
[name] => Bagan Pete
[code] => 36129, 36127
[code_name] => 36129, 36127 - Bagan Pete
)
)
Please try below one as another approach:
<?php
$arr = Array (
Array
(
'name' => 'Jambi Selatan',
'code' => '36139',
'code_name' => '36139 - Jambi Selatan'
),
Array
(
'name' => 'Jambi Selatan',
'code' => '36137',
'code_name' => '36137 - Jambi Selatan'
),
Array
(
'name' => 'Bagan Pete',
'code' => '36129',
'code_name' => '36129 - Bagan Pete'
),
Array
(
'name' => 'Bagan Pete',
'code' => '36127',
'code_name' => '36127 - Bagan Pete'
)
);
$newarr = array();
$finalArr = array();
foreach($arr as $aa) {
$newarr[$aa['name']][] = $aa;
}
foreach($newarr as $kk => $bb) {
foreach($bb as $cc) {
$finalArr[$kk]['name'] = $cc['name'];
if(isset($finalArr[$kk]['code'])) {
$finalArr[$kk]['code'] = $finalArr[$kk]['code'].','.$cc['code'];
} else {
$finalArr[$kk]['code'] = $cc['code'];
}
if(isset($finalArr[$kk]['code_name'])) {
$finalArr[$kk]['code_name'] = $finalArr[$kk]['code_name'].','.$cc['code_name'];
} else {
$finalArr[$kk]['code_name'] = $cc['code_name'];
}
}
}
echo "<pre>";
print_r($finalArr);
echo "</pre>";
?>
Definitely avoid any suggestions that use more than one loop to group and concatenate the data.
I do endorse #Opsional's snippet. An alternative approach is to push reference variables into the result array, then only concatenate comma-separated values to the appropriate reference variable.
Code: (Demo)
$result = [];
foreach ($arr as $row) {
if (!isset($ref[$row['name']])) {
$ref[$row['name']] = $row;
$result[] = &$ref[$row['name']];
} else {
$ref[$row['name']]['code'] .= ', ' . $row['code'];
$ref[$row['name']]['code_name'] .= ', ' . $row['code_name'];
}
}
var_export($result);
For any purist developers that insist on destroying references, call unset($ref) after the loop.
Here is a streamlined version of #Opsional's snippet: (Demo)
$result = [];
foreach ($arr as $row) {
if (!isset($result[$row['name']])) {
$result[$row['name']] = $row;
} else {
$result[$row['name']]['code'] .= ', ' . $row['code'];
$result[$row['name']]['code_name'] .= ', ' . $row['code_name'];
}
}
var_export(array_values($result));

How to create variables using a php array?

I have a PHP array, something like below:
Array(
[0] => Array
(
[name] => month_year
[value] => 201609
)
[1] => Array
(
[name] => advance_amount
[value] => 50%
)
)
Using this array, I want to create 2 variables like this:
$month_year = '201609';
$advance_amount = '50%';
Can anybody tell me is this possible in php?
I tried it using two foreach but I don't have any idea how to precced.
foreach ($_POST as $k => $data) {
//echo "<pre>", print_r($data)."</pre>";
foreach ($data as $key => $value) {
echo $key."<br>";
}
}
Use variable variables. Your foreach loop should be like this:
foreach ($_POST as $k => $data) {
$$data['name'] = $data['value'];
}
// display variables
echo $month_year . "<br />";
echo $advance_amount;
PHP7 style:
$a = [['name' = 'month_year', 'value' => '201609'], ['name' => 'advance_amount', 'value' => '50%']];
foreach ($a as $line) {
${$line['name']} = $line['value'];
}
php > echo $month_year; //201609
Have a look at the Variables reference
Caution
Further dereferencing a variable property that is an array has
different semantics between PHP 5 and PHP 7. The PHP 7.0 migration
guide includes further details on the types of expressions that have
changed, and how to place curly braces to avoid ambiguity.
using list it gives you the cleaner way to solve the issue: for example
$data = [
[
'name' => 'month_year',
'value' => 201609
],
[
'name' => 'advance_amount',
'value' => '50%'
]
];
list($month_year, $advance_amount) = array_map(function($value){
return $value['value'];
}, $data);
echo sprintf('Month of the year is %s with porcentage %s', $month_year, $advance_amount);
This will have the result you are looking for with a clearer code.
Month of the year is 201609 with porcentage 50%
first create loop and declare var.
$data = array(array(
'name' => 'month_year',
'value' => 201609,
), array(
'name' => 'advance_amount',
'value' => '50%',
)
);
foreach ($data as $key => $value) {
${$value['name']} = $value['value'];
}
echo $month_year;
echo '<br>';
echo $advance_amount;

How to foreach multidimensional array with key value

I have a multidimensional array with key value. I want to loop the data in that array but I don't know how.
This is my array:
$myArray= Array
(
'134' => Array
(
'1138' => Array
(
'id' => 1138,
'qty' => 1,
'price' => 4900000,
'name' => 'Pioneer AVH X5850BT Head Unit Double Din 7Inch',
'options' => Array
(
'image' => '865e6ad631fa45d408acfc6f8a8ff008.jpg',
'created_by' => 134
),
'rowid' => 'f9e62f7ce9665a25ff40848744dd83f4',
'subtotal' => 4900000
),
'1003' => Array
(
'id' => 1003,
'qty' => 1,
'price' => 2250000,
'name' => 'Steelmate SW813 Subwoofer Aktif 10 Inch',
'options' => Array
(
'image' => '962df806d5adc7bd0d22666fe996f139.jpg',
'created_by' => 134
),
'rowid' => '7aa455ef597b2906e3895783bd7a5c70',
'subtotal' => 2250000
)
),
'157' => Array
(
'2527' => Array
(
'id' => 2527,
'qty' => 1,
'price' => 2475000,
'name' => 'Rockford Fosgate P165SE Speaker Split 2way Komponen',
'options' => Array
(
'image' => '81027273a2ad59a96aec85ec66ce2704.jpg',
'created_by' => 157
),
'rowid' => 'ed9301accd0d84bd0417609aa80cebc7',
'subtotal' => 2475000
)
)
);
How do I loop / foreach that array?
I guess there is a foreach inside a foreach, but I don't know how to do that.
You can use a recursive function here, so you don't need to worry how deep your array will be.
Something like this:
function read($arr) {
foreach ($arr as $key => $value) {
if (is_array($value)) {
read($a);
}
else {
// You cann access key and value here (for each array)
}
}
}
read($myArray);
Just use another foreach inside your foreach
foreach ($myArray as $key => $value) {
foreach ($value as $subkey => $subvalue) {
if (is_array($subvalue)) {
foreach ($subvalue as $subsubkey => $subsubvalue) {
// .... and so on
}
}
}
}
/* loop across $myArray (listing elements 134 and 157) */
foreach ($myArray as $groupId => $group) {
echo "walking through group $groupId" . PHP_EOL;
/* loop across "groups" 134 and 157 (listing elements 1138, 1003, etc.) */
foreach ($group as $itemId => $item) {
echo "walking through item $itemId" . PHP_EOL;
/* loop each "item" record in key/value pairs */
foreach ($item as $key => $value) {
echo "$key: ";
/* deal with options sub-array */
if (is_array($value)) {
foreach ($value as $option => $optionValue) {
echo " $option: $optionValue" . PHP_EOL;
}
} else {
echo $value . PHP_EOL;
}
}
}
}

How do I get corresponding keys to another key from multidimensional array?

I have a multidimensional array in the following format:
$array = array (
0 =>
array (
'date' => '2013-03-25',
'name' => 'Bob',
'time' => '11'
),
1 =>
array (
'date' => '2013-03-25',
'name' => 'Brian',
'time' => '13'
),
2 =>
array (
'date' => '2013-03-26',
'name' => 'Jack',
'time' => '14'
),
3 =>
array (
'date' => '2013-03-26',
'name' => 'Bob',
'time' => '14'
)
);
I am trying to get the names and corresponding times for each date. I have got the names using the following method:
$array2 = array();
foreach($array as $item) {
$array2[$item['date']][] = $item['name'];
}
and then using:
foreach($array2[$date] as $name)
to run a query on the names returned. But I am not sure how to get the corresponding 'time' key for each 'name' key in the second foreach loop.
Why you don't want to store both name and time for each date key?
$array2 = array();
foreach ($array as $item) {
$array2[$item['date']] []= array($item['time'], $item['name']);
}
You can reach name and time with this code:
foreach ($array2 as $row) {
$name = $row[0];
$time = $row[1];
}
You can try
$list = array();
foreach ( $array as $k => $item ) {
$list[$item['date']][] = array(
$item['name'],
$item['time']
);
}
foreach ( $list as $date => $data ) {
echo $date, PHP_EOL;
foreach ( $data as $var ) {
list($name, $time) = $var;
echo $name, " ", $time, PHP_EOL;
}
echo PHP_EOL;
}
Output
2013-03-25
Bob 11
Brian 13
2013-03-26
Jack 14
Bob 14
try the following:
foreach($array as $item) {
$array2[$item['date'][] = array('name' => $item['name'], 'time' => $item['time']);
}
foreach($array2[$date] as $name) {
echo $name['name'] . ' => ' . $name['time'] . "\n";
}

PHP Recursively unset array keys if match

I have the following array that I need to recursively loop through and remove any child arrays that have the key 'fields'. I have tried array filter but I am having trouble getting any of it to work.
$myarray = array(
'Item' => array(
'fields' => array('id', 'name'),
'Part' => array(
'fields' => array('part_number', 'part_name')
)
),
'Owner' => array(
'fields' => array('id', 'name', 'active'),
'Company' => array(
'fields' => array('id', 'name',),
'Locations' => array(
'fields' => array('id', 'name', 'address', 'zip'),
'State' => array(
'fields' => array('id', 'name')
)
)
)
)
);
This is how I need it the result to look like:
$myarray = array(
'Item' => array(
'Part' => array(
)
),
'Owner' => array(
'Company' => array(
'Locations' => array(
'State' => array(
)
)
)
)
);
If you want to operate recursively, you need to pass the array as a reference, otherwise you do a lot of unnecessarily copying:
function recursive_unset(&$array, $unwanted_key) {
unset($array[$unwanted_key]);
foreach ($array as &$value) {
if (is_array($value)) {
recursive_unset($value, $unwanted_key);
}
}
}
you want array_walk
function remove_key(&$a) {
if(is_array($a)) {
unset($a['fields']);
array_walk($a, __FUNCTION__);
}
}
remove_key($myarray);
My suggestion:
function removeKey(&$array, $key)
{
if (is_array($array))
{
if (isset($array[$key]))
{
unset($array[$key]);
}
if (count($array) > 0)
{
foreach ($array as $k => $arr)
{
removeKey($array[$k], $key);
}
}
}
}
removeKey($myarray, 'Part');
function recursive_unset(&$array, $unwanted_key) {
if (!is_array($array) || empty($unwanted_key))
return false;
unset($array[$unwanted_key]);
foreach ($array as &$value) {
if (is_array($value)) {
recursive_unset($value, $unwanted_key);
}
}
}
function sanitize($arr) {
if (is_array($arr)) {
$out = array();
foreach ($arr as $key => $val) {
if ($key != 'fields') {
$out[$key] = sanitize($val);
}
}
} else {
return $arr;
}
return $out;
}
$myarray = sanitize($myarray);
Result:
array (
'Item' =>
array (
'Part' =>
array (
),
),
'Owner' =>
array (
'Company' =>
array (
'Locations' =>
array (
'State' =>
array (
),
),
),
),
)
function removeRecursive($haystack,$needle){
if(is_array($haystack)) {
unset($haystack[$needle]);
foreach ($haystack as $k=>$value) {
$haystack[$k] = removeRecursive($value,$needle);
}
}
return $haystack;
}
$new = removeRecursive($old,'key');
Code:
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => $sweet);
function recursive_array_except(&$array, $except)
{
foreach($array as $key => $value){
if(in_array($key, $except, true)){
unset($array[$key]);
}else{
if(is_array($value)){
recursive_array_except($array[$key], $except);
}
}
}
return;
}
recursive_array_except($fruits, array('a'));
print_r($fruits);
Input:
Array
(
[sweet] => Array
(
[a] => apple
[b] => banana
)
[sour] => Array
(
[a] => apple
[b] => banana
)
)
Output:
Array
(
[sweet] => Array
(
[b] => banana
)
[sour] => Array
(
[b] => banana
)
)
I come up with a simple function that you can use to delete multiple array element based on multiple keys.
Detail example here.
Just a little change in code.
function removeRecursive($inputArray,$delKey){
if(is_array($inputArray)){
$moreKey = explode(",",$delKey);
foreach($moreKey as $nKey){
unset($inputArray[$nKey]);
foreach($inputArray as $k=>$value) {
$inputArray[$k] = removeRecursive($value,$nKey);
}
}
}
return $inputArray;
}
$inputNew = removeRecursive($input,'keyOne,keyTwo');
print"<pre>";
print_r($inputNew);
print"</pre>";
Give this function a shot. It will remove the keys with 'fields' and leave the rest of the array.
function unsetFields($myarray) {
if (isset($myarray['fields']))
unset($myarray['fields']);
foreach ($myarray as $key => $value)
$myarray[$key] = unsetFields($value);
return $myarray;
}
Recursively walk the array (by reference) and unset the relevant keys.
clear_fields($myarray);
print_r($myarray);
function clear_fields(&$parent) {
unset($parent['fields']);
foreach ($parent as $k => &$v) {
if (is_array($v)) {
clear_fields($v);
}
}
}
I needed to have a little more granularity in unsetting arrays and I came up with this - with the evil eval and other dirty tricks.
$post = array(); //some huge array
function array_unset(&$arr,$path){
$str = 'unset($arr[\''.implode('\'][\'',explode('/', $path)).'\']);';
eval($str);
}
$junk = array();
$junk[] = 'property_meta/_edit_lock';
$junk[] = 'property_terms/post_tag';
$junk[] = 'property_terms/property-type/0/term_id';
foreach($junk as $path){
array_unset($post,$path);
}
// unset($arr['property_meta']['_edit_lock']);
// unset($arr['property_terms']['post_tag']);
// unset($arr['property_terms']['property-type']['0']['term_id']);

Categories