How to read nested array values without knowing the keys? - php

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

Related

PHP different 2 arrays and use conditions in comparison

I have 2 arrays follow this:
Array A
Array
(
[0] => Array
(
[TD_CODE] => 24203
[CRS_NAME] => Adobe Photoshop CS6+CC
)
[1] => Array
(
[TD_CODE] => 24202
[CRS_NAME] => Advance Microsoft excel 2010/2007
)
[2] => Array
(
[TD_CODE] => 24197
[CRS_NAME] => Beginning Auditor Tools and Techniques
)
);
And Array B
Array
(
[0] => Array
(
[crs_id] => 1
[crs_ia_id] => 2017-6495
[crs_oracle_id] => 24653
[crs_name] => Windows8
[crs_start_date] => 2017-08-07
[crs_end_date] => 2017-08-11
)
[1] => Array
(
[crs_id] => 2
[crs_ia_id] => 2017-5013
[crs_oracle_id] => 24202
[crs_name] => Advance Microsoft excel 2010/2007
[crs_start_date] => 2017-02-08
[crs_end_date] => 2017-02-09
)
)
I want to make array A different array B.
The condition is to use TD_CODE of the array A compared to crs_oracle_id of array b And and take it as array C.
So The results are as follows.
Array
(
[0] => Array
(
[TD_CODE] => 24203
[CRS_NAME] => Adobe Photoshop CS6+CC
)
[1] => Array
(
[TD_CODE] => 24197
[CRS_NAME] => Beginning Auditor Tools and Techniques
)
);
How should I do?
You can use array_filter() with anonymous function to compare TD_CODE and crs_oracle_id
$array_c = array_filter($array_a, function($e) use($array_b) {
foreach ($array_b as $v) {
if ($v['crs_oracle_id'] == $e['TD_CODE']) {
return false;
}
}
return true;
});
print_r($array_c);
Get ids from second array which needs to be rejected, then add only those records which doesn't exists in this id array,
$rejected_ids = array_column($b,'crs_oracle_id');
$c = [];
foreach($a as $v){
if(!in_array($v['TD_CODE'], $rejected_ids)){
$c[] = $v;
}
}
print_r($c);
array_column — Return the values from a single column in the input array
Here is working demo
EDIT
Here is more optimized code,
$c = array_filter($a, function($v,$k) use($rejected_ids){
return !in_array($v['TD_CODE'], $rejected_ids);
},ARRAY_FILTER_USE_BOTH);
Here is working demo.
array_filter — Filters elements of an array using a callback function
ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to callback instead of the value
If your PHP Version is below 5.5 Then Please use this function
if (! function_exists('array_column')) {
function array_column(array $input, $columnKey, $indexKey = null) {
$array = array();
foreach ($input as $value) {
if ( !array_key_exists($columnKey, $value)) {
trigger_error("Key \"$columnKey\" does not exist in array");
return false;
}
if (is_null($indexKey)) {
$array[] = $value[$columnKey];
}
else {
if ( !array_key_exists($indexKey, $value)) {
trigger_error("Key \"$indexKey\" does not exist in array");
return false;
}
if ( ! is_scalar($value[$indexKey])) {
trigger_error("Key \"$indexKey\" does not contain scalar value");
return false;
}
$array[$value[$indexKey]] = $value[$columnKey];
}
}
return $array;
}
}
ARRAY - A
$array_a = Array
(
'0' => Array
(
'TD_CODE' => '24203',
'CRS_NAME' => 'Adobe Photoshop CS6+CC'
),
'1' => Array
(
'TD_CODE' => '24202',
'CRS_NAME' => 'Advance Microsoft excel 2010/2007'
),
'2' => Array
(
'TD_CODE' => '24197',
'CRS_NAME' => 'Beginning Auditor Tools and Techniques'
)
);
ARRAY - B
$array_b = Array
(
'0' => Array
(
'crs_id' => '1',
'crs_ia_id' => '2017-6495',
'crs_oracle_id' => '24653',
'crs_name' => 'Windows8',
'crs_start_date' => '2017-08-07',
'crs_end_date' => '2017-08-11'
),
'1' => Array
(
'crs_id' => '2',
'crs_ia_id' => '2017-5013',
'crs_oracle_id' => '24202',
'crs_name' => 'Advance Microsoft excel 2010/2007',
'crs_start_date' => '2017-02-08',
'crs_end_date' => '2017-02-09'
)
);
ARRAY - C
$array_c = array();
foreach ($array_a as $a){
if(!in_array($a['TD_CODE'], array_column($array_b, 'crs_oracle_id'))) {
$array_c[] = array('TD_CODE' => $a['TD_CODE'],'CRS_NAME'=>$a['CRS_NAME']);
}
}
print_r($array_c);

Php string comparision in multidimensional array

I have two multidimensional array
Array
(
[0] => Array
(
[code] => 2079
[label] => Nike
)
[1] => Array
(
[code] => 1080
[label] => Adidas
)
)
Array
(
[0] => Array
(
[manufacturers_id] => 2753
[manufacturers_name] => Reebok
)
[1] => Array
(
[manufacturers_id] => 2526
[manufacturers_name] => Adidas
)
[2] => Array
(
[manufacturers_id] => 34
[manufacturers_name] => Nike
)
)
I want to do string matching of a key label of array 1 with key manufacturer_name of array 2. What is the best approach in multidimensional arrays ?
You could loop trough the arrays.
foreach ($multi_array1 as $value) {
foreach ($multi_array2 as $value2) {
If ($value[label] === $value2 [manufacturer_name])
{}
}
}
If you want to match by label and manufacturers_name, then I suggest you reindex your arrays by those fields:
$by_label = [];
foreach($first_array as $element) {
$by_label[$element['label']] = $element['code'];
}
$by_name = [];
foreach($second_array as $element) {
$by_label[$element['manufacturers_name']] = $element['manufacturers_id'];
}
foreach($by_label as $label => $code) {
print "Label is $label, code is $code, id is {$by_name[$label]}";
}
foreach($by_name as $name => $id) {
print "Name is $name, id is $id, label is {$by_label[$name]}";
}
Just use foreach to accomplish your desire result.
Array
$firstArr = array(
array("code" => 2079, "label" => 'Nike'),
array("code" => 1080, "label" => 'Adidas')
);
$secArr = array(
array("manufacturers_id" => 2753, "manufacturers_name" => 'Reebok'),
array("manufacturers_id" => 2526, "manufacturers_name" => 'Adidas'),
array("manufacturers_id" => 34, "manufacturers_name" => 'Nike')
);
Foreach Technique:
foreach($firstArr as $value){
if(in_array_sec($value['label'])){
echo $value['label'].' found in second array.';
}else{
echo $value['label'].' not found in second array.';
}
}
function in_array_sec($val_one){
global $secArr;
$flag = false;
foreach($secArr as $value){
if($value['manufacturers_name'] == $val_one){
$flag = true;
break;
}
else
$flag = false;
}
return $flag;
}
Result:
Nike found in second array.
Adidas found in second array.

How to filter a two dimensional array by value

How would I create a function that filters a two dimensional array by value?
Given the following array :
Array
(
[0] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => CarEnquiry
[status] => NEW
[appointment] => 0
)
[1] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => CarEnquiry
[status] => CALL1
[appointment] => 0
)
[2] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => Finance
[status] => CALL2
[appointment] => 0
)
[3] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => Partex
[status] => CALL3
[appointment] => 0
)
How would I filter the array to only show those arrays that contain a specific value in the name key? For example name = 'CarEnquiry'.
The resulting output would be:
Array
(
[0] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => CarEnquiry
[status] => NEW
[appointment] => 0
)
[1] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => CarEnquiry
[status] => CALL1
[appointment] => 0
)
)
EDIT
I forgot to mention that the search value should be interchangeable - i.e. name = 'CarEnquiry' or name = 'Finance'.
Use PHP's array_filter function with a callback.
$new = array_filter($arr, function ($var) {
return ($var['name'] == 'CarEnquiry');
});
Edit: If it needs to be interchangeable, you can modify the code slightly:
$filterBy = 'CarEnquiry'; // or Finance etc.
$new = array_filter($arr, function ($var) use ($filterBy) {
return ($var['name'] == $filterBy);
});
If you want to make this a generic function use this:
function filterArrayByKeyValue($array, $key, $keyValue)
{
return array_filter($array, function($value) use ($key, $keyValue) {
return $value[$key] == $keyValue;
});
}
<?php
function filter_array($array,$term){
$matches = array();
foreach($array as $a){
if($a['name'] == $term)
$matches[]=$a;
}
return $matches;
}
$new_array = filter_array($your_array,'CarEnquiry');
?>
Above examples are using the exact word match, here is a simple example for filtering array to find imprecise "name" match.
$options = array_filter($options, function ($option) use ($name) {
return strpos(strtolower($option['text']), strtolower($name)) !== FALSE;
});
array_filter is the function you need. http://php.net/manual/en/function.array-filter.php
Give it a filtering function like this:
function my_filter($elt) {
return $elt['name'] == 'something';
}
function multi_array_search_with_condition($array, $condition)
{
$foundItems = array();
foreach($array as $item)
{
$find = TRUE;
foreach($condition as $key => $value)
{
if(isset($item[$key]) && $item[$key] == $value)
{
$find = TRUE;
} else {
$find = FALSE;
}
}
if($find)
{
array_push($foundItems, $item);
}
}
return $foundItems;
}
This my function can use about this problem. You can use:
$filtered = multi_array_search_with_condition(
$array,
array('name' => 'CarEnquiry')
);
This will get your filtered items from your 2 dimensional array.

array_values recursive 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

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