array_values recursive php - php

Let's say I have an array like this:
Array
(
[id] => 45
[name] => john
[children] => Array
(
[45] => Array
(
[id] => 45
[name] => steph
[children] => Array
(
[56] => Array
(
[id] => 56
[name] => maria
[children] => Array
(
[60] => Array
(
[id] => 60
[name] => thomas
)
[61] => Array
(
[id] => 61
[name] => michelle
)
)
)
[57] => Array
(
[id] => 57
[name] => luis
)
)
)
)
)
What I'm trying to do is to reset the keys of the array with keys children to 0, 1, 2, 3, and so on, instead of 45, 56, or 57.
I tried something like:
function array_values_recursive($arr)
{
foreach ($arr as $key => $value)
{
if(is_array($value))
{
$arr[$key] = array_values($value);
$this->array_values_recursive($value);
}
}
return $arr;
}
But that reset only the key of the first children array (the one with key 45)

function array_values_recursive($arr)
{
$arr2=[];
foreach ($arr as $key => $value)
{
if(is_array($value))
{
$arr2[] = array_values_recursive($value);
}else{
$arr2[] = $value;
}
}
return $arr2;
}
this function that implement array_values_recursive from array like:
array(
'key1'=> 'value1',
'key2'=> array (
'key2-1'=>'value-2-1',
'key2-2'=>'value-2-2'
)
);
to array like:
array(
0 => 'value1',
1 => array (
0 =>'value-2-1',
1 =>'value-2-2'
)
);

You use a recursive approach but you do not assign the return value of the function call $this->array_values_recursive($value); anywhere. The first level works, as you modify $arr in the loop. Any further level does not work anymore for mentioned reasons.
If you want to keep your function, change it as follows (untested):
function array_values_recursive($arr)
{
foreach ($arr as $key => $value)
{
if (is_array($value))
{
$arr[$key] = $this->array_values_recursive($value);
}
}
if (isset($arr['children']))
{
$arr['children'] = array_values($arr['children']);
}
return $arr;
}

This should do it:
function array_values_recursive($arr, $key)
{
$arr2 = ($key == 'children') ? array_values($arr) : $arr;
foreach ($arr2 as $key => &$value)
{
if(is_array($value))
{
$value = array_values_recursive($value, $key);
}
}
return $arr2;
}

Try this ,
function updateData($updateAry,$result = array()){
foreach($updateAry as $key => $values){
if(is_array($values) && count($values) > 0){
$result[$key] = $this->_updateData($values,$values);
}else{
$result[$key] = 'here you can update values';
}
}
return $result;
}

You can used php fnc walk_array_recursive
Here

Related

How to read nested array values without knowing the keys?

I'm new in array. I wish to print out the values of all possible [type] [label] [value]. I wish to do like "if there's a type with select, then display all labels with values"
Below is my array.
Array
(
[product_id] => 8928
[title] => Example of a Product
[groups] => Array
(
[8929] => Array
(
[8932] => Array
(
[type] => select
[label] => Section
[id] => pewc_group_8929_8932
[group_id] => 8929
[field_id] => 8932
[value] => Section 200
[flat_rate] => Array
(
)
)
)
)
[price_with_extras] => 0
[products] => Array
(
[field_id] => pewc_group_8929_9028
[child_products] => Array
(
[8945] => Array
(
[child_product_id] => Array
(
[0] => 8945
)
[field_id] => pewc_group_8929_9028
[quantities] => one-only
[allow_none] => 0
)
)
[pewc_parent_product] => 8928
[parent_field_id] => pewc_5d678156d81c6
)
)
The site is saying "
It looks like your post is mostly code; please add some more details." So here's my so-called lorem ipsum :D
You can use array_walk_recursive for the same,
array_walk_recursive($arr, function ($value, $key) {
// check if key matches with type, label or value
if (count(array_intersect([$key], ['type', 'label', 'value'])) > 0) {
echo "[$value] ";
}
});
Demo
Output
[select] [Section] [Section 200]
EDIT
You can modify the condition as,
if($key === 'type' && $value == 'select')
EDIT 1
array_walk_recursive($arr, function ($value, $key) {
if($key === 'type' && $value == 'select'){
echo "[$value] ";
}
});
EDIT 2
function search_by_key_value($arr, $key, $value)
{
$result = [];
if (is_array($arr)) {
if (isset($arr[$key]) && $arr[$key] == $value) {
$result[] = $arr;
}
foreach ($arr as $value1) {
$result = array_merge($result, search_by_key_value($value1, $key, $value));
}
}
return $result;
}
// find array by key = type and value = select
$temp = search_by_key_value($arr, 'type', 'select');
$temp = array_shift($temp);
print_r($temp);
echo $temp['label'];
echo $temp['value'];
Demo

Simplify Array Duplicate Element in Array PHP

How can we find the count of duplicate elements in a multidimensional array,
I have an array like this:
Array
(
[0] => Array
(
[brti] => 29
)
[1] => Array
(
[voda] => 6
)
[2] => Array
(
[btel] => 8
)
[3] => Array
(
[btel] => 10
)
)
Question: How to simplify the structure of array, i mean can be counting the value if there is indicate that have same key ?
just like this:
Array
(
[0] => Array
(
[brti] => 29
)
[1] => Array
(
[voda] => 6
)
[2] => Array
(
[btel] => 18
)
)
So far, i've tried this way, but it didn't help me. My array is store in $test
$test = [sample array]
$count = array();
foreach ($test as $key => $value) {
foreach ($value as $k => $val) {
if (isset($count[$val])) {
++$count[$val];
} else {
$count[$value] = 1;
}
}
}
print_r($count);
<?php
$array = [
"0" => ["brti" => 29],
"1" => ["voda" => 6],
"2" => ["btel" => 8],
"3" => ["btel" => 10],
];
$final = array();
array_walk_recursive($array, function($item, $key) use (&$final){
$final[$key] = isset($final[$key]) ? $item + $final[$key] : $item;
});
print_r($final);
});
check demo
You can do it in very simple way,
$test = [];
foreach ($array as $value)
{
foreach ($value as $k => $v)
{
// $test[$k] = ($test[$k] ?? 0); // initialised if not php 7+
$test[$k] = (empty($test[$k]) ? 0: $test[$k]); // below php 7
$test[$k] += $v;
}
}
print_r($test);
Output:
Array
(
[brti] => 29
[voda] => 6
[btel] => 18
)
Working demo.

sorting an array which its values are associate array

I have an array that its values are associate arrays. I need sort this array based on keys;
$list = array (
array("post_id"=>"2","date"=>"2015","title"=>"title2"),
array("post_id"=>"4","date"=>"2017","title"=>"title4"),
array("post_id"=>"3","date"=>"2016","title"=>"title3"),
array("post_id"=>"1","date"=>"2014","title"=>"title1")
);
For example sorting this array by post_id which means turn that array to this:
$list = array (
array("post_id"=>"1","date"=>"2014","title"=>"title1"),
array("post_id"=>"2","date"=>"2015","title"=>"title2"),
array("post_id"=>"3","date"=>"2016","title"=>"title3"),
array("post_id"=>"4","date"=>"2017","title"=>"title4")
);
I searched this forum and find this code:
function array_sort($array, $on, $order=SORT_ASC){
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;}
but I cant understand what is it exactly doing.
the topic link is:
Sort PHP multi-dimensional array based on key?
You're not sorting by key, so the example you found won't work for you. A simple usort will do it;
$list = array (
array("post_id"=>"2","date"=>"2015","title"=>"title2"),
array("post_id"=>"4","date"=>"2017","title"=>"title4"),
array("post_id"=>"3","date"=>"2016","title"=>"title3"),
array("post_id"=>"1","date"=>"2014","title"=>"title1")
);
function sortPosts($a, $b)
{
if ($a['post_id'] == $b['post_id']) {
return 0;
}
return ($a['post_id'] < $b['post_id']) ? -1 : 1;
}
usort($list, "sortPosts");
This passes your $lists array into a function and compares each of its values - you can see we're comparing the ['post_id'] value for each.
As the post_id's are strings in your original array, you may need to typecast these as integers, but see how you go.
I use this function :
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
return $array;
}
$list = array (
array("post_id"=>"2","date"=>"2015","title"=>"title2"),
array("post_id"=>"4","date"=>"2017","title"=>"title4"),
array("post_id"=>"3","date"=>"2016","title"=>"title3"),
array("post_id"=>"1","date"=>"2014","title"=>"title1")
);
$outputArray = aasort($list,"post_id");
Most elegant usually is to use the usort() function combined with a closure.
Take a look at this simple demonstration:
<?php
$list = [
["post_id"=>"2","date"=>"2015","title"=>"title2"],
["post_id"=>"4","date"=>"2017","title"=>"title4"],
["post_id"=>"3","date"=>"2016","title"=>"title3"],
["post_id"=>"1","date"=>"2014","title"=>"title1"]
];
usort(
$list,
function($a, $b) {
return $a['post_id'] < $b['post_id'];
}
);
print_r($list); // First output, descending order
usort(
$list,
function($a, $b) {
return $a['post_id'] > $b['post_id'];
}
);
print_r($list); // Second output, ascending order
Note the reversed comparison operator in the two calls, < versus >...
The output of that obviously is:
First output, descending order:
Array
(
[0] => Array
(
[post_id] => 4
[date] => 2017
[title] => title4
)
[1] => Array
(
[post_id] => 3
[date] => 2016
[title] => title3
)
[2] => Array
(
[post_id] => 2
[date] => 2015
[title] => title2
)
[3] => Array
(
[post_id] => 1
[date] => 2014
[title] => title1
)
)
Second output, ascending order:
Array
(
[0] => Array
(
[post_id] => 1
[date] => 2014
[title] => title1
)
[1] => Array
(
[post_id] => 2
[date] => 2015
[title] => title2
)
[2] => Array
(
[post_id] => 3
[date] => 2016
[title] => title3
)
[3] => Array
(
[post_id] => 4
[date] => 2017
[title] => title4
)
)
That probably wasn't the best answer to chose from that question. Just extract the column to sort on, and sort that to sort the original:
array_multisort(array_column($list, 'post_id'), SORT_ASC, $list);
You can use following code:
<?php
$list = array (
array("post_id"=>"2","date"=>"2015","title"=>"title2"),
array("post_id"=>"4","date"=>"2017","title"=>"title4"),
array("post_id"=>"3","date"=>"2016","title"=>"title3"),
array("post_id"=>"1","date"=>"2014","title"=>"title1")
);
$sorted = array_orderby($list, 'post_id', SORT_ASC);
echo "<pre>";
print_r($sorted);
function array_orderby()
{
$args = func_get_args();
$data = array_shift($args);
foreach ($args as $n => $field) {
if (is_string($field)) {
$tmp = array();
foreach ($data as $key => $row)
$tmp[$key] = $row[$field];
$args[$n] = $tmp;
}
}
$args[] = &$data;
call_user_func_array('array_multisort', $args);
return array_pop($args);
}
?>
It will produce following output:
Array
(
[0] => Array
(
[post_id] => 1
[date] => 2014
[title] => title1
)
[1] => Array
(
[post_id] => 2
[date] => 2015
[title] => title2
)
[2] => Array
(
[post_id] => 3
[date] => 2016
[title] => title3
)
[3] => Array
(
[post_id] => 4
[date] => 2017
[title] => title4
)
)
The function in
OP question does:
first collects all values via $on from the subarray (first foreach) and binds it to the $sortable_array via original_array key $k. Like $list[0]['post_id']; is collect in: $sortable_array[0];
After all values are collected, the array will be sorted DESC or ASC (see switch) with asort, that keeps the index=>value connection. So $sortable_array looks like: Before [0=>2,1=>4,2=>3,3=>1] After [3=>1,0=>2,2=>3,1=>4]
So now the values are sorted and the index can be used in the next step.
In the last foreach a new array is generated. The index $k from the $sortable_array is used to get the subsarrays from the original_array in the new order.
note: This part if (is_array($v)) makes the function behavior not predictable, because it takes just the $v if $v is not an subarray else it would take data from the subarray!!!

PHP search_array for multi dimension array

how to get the index of a children array for an array look like this:
Array
(
[1000] => Array
(
[firstName] => Ori
[lastName] => Smith
[children] => Array
(
[0] => 1001
[1] => 1002
[2] => 1003
[3] => 1004
[4] => 1005
[5] => 1006
[6] => 1007
[7] => 1008
[8] => 1009
[9] => 1010
)
)
)
so if I give 1009 as the search, it should return 1000.
It does not work with this code:
array_search($childrenId, array_column(myArray, 'children'));
Try this
$result = array(
'1000'=>array('children'=>array('1001','1002')),
'2000'=>array('children'=>array('2001','2002'))
);
$searchValue = 2001;
$keyName = '';
foreach ($result as $key => $row) {
foreach ($row['children'] as $child) {
if ($child == $searchValue) {
$keyName = $key;
break;
}
}
}
echo $keyName;
You can use this function found here:
function getParentStack($child, $stack) {
foreach ($stack as $k => $v) {
if (is_array($v)) {
// If the current element of the array is an array, recurse it and capture the return
$return = getParentStack($child, $v);
// If the return is an array, stack it and return it
if (is_array($return)) {
return array($k => $return);
}
} else {
// Since we are not on an array, compare directly
if ($v == $child) {
// And if we match, stack it and return it
return array($k => $child);
}
}
}
// Return false since there was nothing found
return false;
}
I guess you could get the key by key(getParentStack(1009, $myarr)) or modify the function.

removing array empty value

foreach ($this->CsInventory as $value)
{
print_r($value) // print 1
$vname = $value[] = $value['VesselName'];
$total = $value[] = $value['Total'];
$Box = $value[] = $value['Box'];
print_r($value); // print 2
$rdata .= '<td>'.$vname.'</td>
<td>'.$total.'</td>
<td>'.$Box.'</td>';
}
Print 1
Array
(
[VesselName] => MARIANNE
[Total] => 13838
[Box] => 1156
)
Array
(
[Box] => 154
)
Array
(
[Box] => 3825
)
Array
(
[Box] => 50571
)
print 2
Array
(
[VesselName] => MARIANNE
[Total] => 15452
[Box] => 1156
[0] => MARIANNE
[1] => 15452
[2] => 1156
)
Array
(
[Box] => 2276
[0] =>
[1] =>
[2] => 2276
)
Array
(
[Box] => 3825
[0] =>
[1] =>
[2] => 3825
)
Array
(
[Box] => 49235
[0] =>
[1] =>
[2] => 49235
)
i how can i remove an empty value in the array? i try many ways but i can get any solution.. so decide to here in the forum?
I'd try to reduce effort.
foreach ($this->CsInventory as $value)
{
foreach ($value as $key => $item)
{
$value[] = $item;
$rdata .= "<td>$item</td>";
}
print_r($value)
}
As a general comment, not sure why you're adding anonomous values back to the $values stack, might be better to use a different array.
If you have specific array elements you want to get rid of, you can use unset($array[$key]);
You could also prevent them getting into the array in the first place by using
if($value['VesselName']) {$vname = $value[] = $value['VesselName'];}
instead of simply
$vname = $value[] = $value['VesselName'];
function array_remove_empty($arr){
$narr = array();
while(list($key, $val) = each($arr)){
if (is_array($val)){
$val = array_remove_empty($val);
// does the result array contain anything?
if (count($val)!=0){
// yes :-)
$narr[$key] = $val;
}
}
else {
if (trim($val) != ""){
$narr[$key] = $val;
}
}
}
unset($arr);
return $narr;
}
array_remove_empty(array(1,2,3, '', array(), 4)) => returns array(1,2,3,4)

Categories