How do I get values from this array? PHP - php

Very much new to PHP and completely stuck because of #attributes when trying to pick values out of an array. I have previously converted an xml file into a associative array.
print_r(array_keys($newArray));
Prints:
Array ( [0] => #attributes [1] => rate )
print_r ($newArray);
Prints:
Array (
[#attributes] => Array (
[base] => GBP
[ts] => 1572881347 )
[rate] => Array (
[0] => Array (
[#attributes] => Array (
[code] => AED
[rate] => 4.739532203531
[live] => 0
)
)
[1] => Array (
[#attributes] => Array (
[code] => AFN
[rate] => 100.80144337913
[live] => 0
)
)
[2] => Array (
[#attributes] => Array (
[code] => ALL
[rate] => 142.29721877018
[live] => 0
)
)
[3] => Array (
[#attributes] => Array (
[code] => AMD
[rate] => 614.98298701028
[live] => 0
)
)
How would I specify and print the last value?
[3] => Array ( [#attributes] => Array ( [code] => AMD [rate] => 614.98298701028 [live] => 0.
With the goal to output something like: AMD, 614.98298701028, 0
Thanks

More generally, if you'd want to look-up a currency in your array, you could use following recursive function:
$code = 'AMD'; // set the curncy you want to lookup
forex($code, $newArray); // invoke the recursive function
// output:
//code : AMD
//rate : 614.98298701028
function forex(string $code = '', array $arr = []): void
{
foreach ($arr as $key => $value) {
if (is_array($value) && $key !== '#attributes') {
forex($code, $value);
} else {
if (isset($value['code']) && $value['code'] == $code) {
echo 'code : ' . $value['code'];
echo '<br />';
echo 'rate : ' . $value['rate'];
echo '<br />';
}
}
}
}
working demo

Assuming that your original array is something like this:
$a = array(
'#attributes' => array(
'base' => 'GBP',
'ts' => 1572881347),
'rate' => array(
0 => array(
'#attributes' => array(
'code' => 'AED',
'rate' => 4.739532203531,
'live' => 0,
),
),
1 => array(
'#attributes' => array(
'code' => 'AFN',
'rate' => 100.80144337913,
'live' => 0,
),
),
2 => array(
'#attributes' => array(
'code' => 'ALL',
'rate' => 142.29721877018,
'live' => 0,
),
),
3 => array(
'#attributes' => array(
'code' => 'AMD',
'rate' => 614.98298701028,
'live' => 0,
),
)));
then you can get what you want with this:
$last_rate = sizeof($a['rate']) - 1;
foreach ($a['rate'][$last_rate]['#attributes'] as $key => $value) {
echo "$value ";
}
Which will output:
AMD 614.98298701028 0

If your array will always contain the array values under rate, you can retrieve the last element of the rate array by using end($newArray['rate']).
To output a CSV style string you can simply use implode(', ', $last['#attributes']) or another desired method, such as foreach, to display the values from the last element.
Example: https://3v4l.org/FNuuZ
if ($last = end($newArray['rate'])) {
echo implode(', ', $last['#attributes']);
}
Result:
AMD, 614.98298701028, 0

Related

how to get the last array with a specific key in multidimensional array

I am looking for a function to return an array and all its sub-structure for a specific criteria
Criteria:
php 5.6 compatible
Return the last instance of array with key name of !ENTITY with all
its values in-tact
Sample array:
For the multidimensional array, lets call that $arr, for this example structure it's 6 levels deep, we should not assume it's always 6 levels.
$arr = array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("svg" =>
array(
0 => array("g" => "", "#id" => "Layer_2"),
1 => array("g" => "", "#id" => "Layer_3"),
),
"#version" => 1.2,
"#id" => "Layer_1",
),
"#different" => "layer"
),
"#all" => "layer"
),
"#here" => "layer"
),
"#goes" => "layer"
),
"#else" => "layer"
),
"#something" => "layer"
);
Expected Output:
I would like to return the final array for !ENTITY with it's sub-structure all in-tact. Here is a sample of the expected output:
Array
(
[svg] => Array
(
[0] => Array
(
[g] =>
[#id] => Layer_2
)
[1] => Array
(
[g]
[#id] => Layer_3
)
)
[#version] => 1.2
[#id] => Layer_1
)
You will need to recursively traverse the array and return resultant values if found like below:
<?php
function getLastValueForKey($data, $key){
$res = '';
foreach($data as $k => $value){
$sub_res = is_array($value) ? getLastValueForKey($value, $key) : '';
if($sub_res !== ''){
$res = $sub_res;
}else if($k === $key){
$res = $value;
}
}
return $res;
}
print_r(getLastValueForKey($arr, '!ENTITY'));
Online Demo

foreach loop is not working after print array

I've tried to loop of following array.
Array
(
[mech_info] => Array
(
[make] => Amaka
[0] => Array
(
[year] => 2001
[model] => Array
(
[0] => Test one
[1] => test fix
[2] => Hamour
[3] => Imagica
)
)
[1] => Array
(
[year] => 2002
[model] => Array
(
[0] => Test Two
)
)
[2] => Array
(
[year] => 2014
[model] => Array
(
[0] => Test three
)
)
[3] => Array
(
[year] => 2015
[model] => Array
(
[0] => test four
)
)
)
)
Array
(
[mech_info] => Array
(
[make] => PRI
[0] => Array
(
[year] => 2005
[model] => Array
(
[0] => PRIMODE
[1] => Temp Pri
[2] => primode
[3] => yyy
)
)
)
)
I want to do it with foreach loop. I have tried by following code but it is not show anything except
`print_r($_POST['mech_show']);`.
$all_make_model= $_POST['mech_show'];
$all_make_model_data = $all_make_model['mech_info'];
foreach ($all_make_model_data as $key => $mec_value) {
echo "string";
echo $meta_value['make'];
}
echo "<pre>";
print_r($_POST['mech_show']);
exit();
also not able to go under foreach and data not print in loop.
given me error
Notice: Undefined index: mech_info
Warning: Invalid argument supplied for foreach() in
i also trie this way but
$all_make_model= $_POST['mech_show'];
$all_make_model_data = $_POST['mech_info'];
foreach ($all_make_model as $key => $mec_value) {
echo "<pre>";
print_r($mec_value['make']);
echo "</pre>";
}
echo "<pre>";
print_r($all_make_model['mech_info']);
but it's showing Warning: Illegal string offset 'mech_info' in ..
I don't know if my code is wrong or I'm missing something anyone pls help me.
Thank You
Some change your foreach loop. it $meta_value['make'] should be $mec_value['make']
So,
$all_make_model= $_POST['mech_show'];
//$all_make_model_data = $all_make_model['mech_info'];
foreach ($all_make_model as $key => $mec_value) {
echo "<pre>";
print_r($mec_value['make']);
echo "</pre>";
}
try
$all_array=array("mech_info"=>array("make"=>"Amaka",array("year"=>2001,"model"=>array("one","two","three")),array("year"=>2002,"model"=>array("one","two","three")),array("year"=>2003,"model"=>array("one","two","three")),array("year"=>2004,"model"=>array("one","two","three"))),array("mech_info"=>array("make"=>"PRI",array("year"=>2001,"model"=>array("one","two","three")))));
$all_make_model= $all_array;
//$all_make_model_data = $all_make_model['mech_info'];
//print_r($all_make_model['mech_info']);
foreach ($all_make_model['mech_info'] as $key => $mec_value) {
if(is_numeric($key)) continue;
echo $mec_value; // output Amaka
}
exit();
This Code just work.
To iterate on multiple mech_info, i added a leave in the array, because otherwise you are tring to create multiple object with the same index.
$p = Array('mech_show' => Array(
0 => Array(
'mech_info' => Array(
'make' => 'Amaka',
'0' => Array(
'year' => 2001,
'model' => Array(
0 => 'Test one',
1 => 'test fix',
2 => 'Hamour',
3 => 'Imagica'
)
),
'1' => Array(
'year' => 2002,
'model' => Array(
0 => 'Test Two'
)
),
'2' => Array(
'year' => 2014,
'model' => Array(
0 => 'Test three'
)
),
'3' => Array(
'year' => 2015,
'model' => Array
(
0 => 'test four'
)
)
)
),
1=>Array(
'mech_info' => Array(
'make' => 'PRI',
'0' => Array(
'year' => 2005,
'model' => Array(
0 => 'PRIMODE',
1 => 'Temp Pri',
2 => 'primode',
3 => 'yyy'
)
)
)
)
)
);
$all_make_model= $p['mech_show'];
foreach($all_make_model as $all_make_model_data){
foreach($all_make_model_data as $mech_info)
var_dump($mech_info['make']);
}
where you have to replace $p with $_POST

Clean multidimensional array in php

I struggle to clean a multidimensional array. I find several Q&A:s on this topic but yet I can't get it to work.
The array $overPayments comes out (from a db call) as below.
Array (
[0] => Array (
[invoiceID] => 103080
[invoiceNumber] => 781
[faktBel] => 1500.00
[totalPayed] => 1500.00
[sumPayedOnThisJournal] => 1500.00
[totOPtoday] => 0.00
[totOPbeforeToday] => -1500.00
[totOPthisJournal] => 0.00 )
[1] => Array(
[invoiceID] => 103290
[invoiceNumber] => 7818
[faktBel] => 648.00
[totalPayed] => 893.00
[sumPayedOnThisJournal] => 893.00
[totOPtoday] => 245.00
[totOPbeforeToday] => -648.00
[totOPthisJournal] => 245.00 )
[2] => Array (
[invoiceID] => 103453
[invoiceNumber] => 202071
[faktBel] => 2250.00
[totalPayed] => 2317.00
[sumPayedOnThisJournal] => 2317.00
[totOPtoday] =>67.00
[totOPbeforeToday] => -2250.00
[totOPthisJournal] => 67.00 )
)
What I need to do is loop through the array called $overPayments containing about 200 sub arrays, and remove all "rows" (subarrays) that have $overPayment['totOPthisJournal'] <= 0. So that I end up with a either modified or new multidimensional array where the totOPthisJournal value is > 0.
I think array_filter is what you are after.
$filteredArray = array_filter($overPayments, function($value) {
return $value['totOPthisJournal'] > 0;
});
just try to unset the array index for which 'totOPthisJournal' is <=0
<?php
$array = Array ( '0' => Array ( 'invoiceID' => 103080, 'invoiceNumber' => 781, 'faktBel' => 1500.00,
'totalPayed' => 1500.00,'sumPayedOnThisJournal' => 1500.00, 'totOPtoday' => 0.00,
'totOPbeforeToday' => -1500.00, 'totOPthisJournal' => 0.00 ), '1' => Array( 'invoiceID' => 103290,
'invoiceNumber' => 7818, 'faktBel' => 648.00, 'totalPayed' => 893.00,
'sumPayedOnThisJournal' => 893.00,'totOPtoday' => 245.00, 'totOPbeforeToday' => -648.00,
'totOPthisJournal' => 245.00 ), '2' => Array ( 'invoiceID' => 103453,'invoiceNumber' => 202071,
'faktBel' => 2250.00, 'totalPayed' => 2317.00, 'sumPayedOnThisJournal' => 2317.00,
'totOPtoday' =>67.00, 'totOPbeforeToday' => -2250.00, 'totOPthisJournal' => 67.00));
foreach($array as $key=>$value){
if($array[$key]['totOPthisJournal'] <= 0){
unset($array[$key]);
}
}
print_r($array);
Put this array into a foreach loop:
foreach($overPayments as $key => $value) {
if($value['totOPthisJournal'] <= 0) {
$key = null;
}
}
This removes the overPayment where [totOPthisJournal] <= 0.
Hope this helps.

Which PHP Array function should I use?

I have two arrays:
Array
(
[0] => Array
(
[id] => 1
[type] => field
[remote_name] => Title
[my_name] => title
[default_value] => http%3A%2F%2Ftest.com
)
[1] => Array
(
[id] => 2
[type] => field
[remote_name] => BookType
[my_name] => book-type
[default_value] =>
)
[2] => Array
(
[id] => 3
[type] => value
[remote_name] => dvd-disc
[my_name] => dvd
[default_value] =>
)
)
Array
(
[title] => Test
[book-type] => dvd
)
I need to take each key in the second array, match it with the my_name value in the first array and replace it with the corresponding remote_name value of the first array while preserving the value of the second array.
There's got to be some carrayzy function to help!
EDIT: There will also be a few cases that the value of the second array will need to be replaced by the value of the first array's remote_name where the value of the second array matches the value of the first array's my_name. How can I achieve this?
EG: book-type => dvd should turn into BookType => dvd-disc
Like so?:
$first = array(
array(
'id' => 1,
'type' => 'field',
'remote_name' => 'Title',
'my_name' => 'title',
'default_value' => 'http%3A%2F%2Ftest.com',
),
array(
'id' => 2,
'type' => 'field',
'remote_name' => 'BookType',
'my_name' => 'book-type',
'default_value' => '',
),
array(
'id' => 3,
'type' => 'value',
'remote_name' => 'dvd-disc',
'my_name' => 'dvd',
'default_value' => '',
),
);
$second = array(
'title' => 'Test',
'book-type' => 'dvd',
);
$map = array('fields' => array(), 'values' => array());
foreach ($first as $entry) {
switch ($entry['type']) {
case 'field':
$map['fields'][$entry['my_name']] = $entry['remote_name'];
break;
case 'value':
$map['values'][$entry['my_name']] = $entry['remote_name'];
break;
}
}
$new = array();
foreach ($second as $key => $val) {
$new[isset($map['fields'][$key]) ? $map['fields'][$key] : $key] = isset($map['values'][$val]) ? $map['values'][$val] : $val;
}
print_r($new);
Output:
Array
(
[Title] => Test
[BookType] => dvd-disc
)
Explanation:
The first loop collects the my_name/remote_name pairs for fields and values and makes them more accessible.
Like so:
Array
(
[fields] => Array
(
[title] => Title
[book-type] => BookType
)
[values] => Array
(
[dvd] => dvd-disc
)
)
The second loop will traverse $second and use the key/value pairs therein to populate $new. But while doing so will check for key/value duplicates in $map.
Keys or values not found in the map will be used as is.
foreach($arr1 as &$el) {
$el['remote_name'] = $arr2[$el['my_name']];
}
unset($el);
I am not aware of such a carrayzy function, but I know how you could do it:
//$array1 is first array, $array2 is second array
foreach($array1 as $key => $value){
if (isset($value['remote_name'], $value['my_name']) && $value['remote_name'] && $value['my_name']){
$my_name = $value['my_name'];
if (isset($array2[$my_name])) {
$remote_name = $value['remote_name'];
$array2[$remote_name] = $array2[$my_name];
//cleanup
unset($array2[$my_name]);
}
}
}

Merge arrays (PHP)

How combine arrays in this way?
source:
Array
(
[0] => Array
(
[id] => 3
[title] => book
[tval] => 10000
)
[1] => Array
(
[id] => 3
[title] => book
[tval] => 1700
)
[3] => Array
(
[id] => 27
[title] => fruit
[tval] => 3000
)
.......
)
result:
Array
(
[0] => Array
(
[id] => 3
[title] => book
[tval] => 10000,1700
)
[1] => Array
(
[id] => 27
[title] => fruit
[tval] => 3000
)
.......
)
please help to solve this problem,
thanks!!!
sorry for bad english(
This should work:
$result = array();
foreach($array as $elem) {
$key = $elem['id'];
if (isset($result[$key])) {
$result[$key]['tval'] .= ',' . $elem['tval'];
} else {
$result[$key] = $elem;
}
}
This basically groups elements by id, concatenating tvals (separated by ,).
Simply building slightly on user576875's method:
$a = array ( 0 => array ( 'id' => 3,
'title' => 'book',
'tval' => 10000
),
1 => array ( 'id' => 3,
'title' => 'book',
'tval' => 1700
),
3 => array ( 'id' => 27,
'bcalias' => 'fruit',
'tval' => 3000
)
);
$result = array();
foreach ($a as $elem) {
$key = $elem['id'];
if (isset($result[$key])) {
$result[$key]['tval'] .= ',' . $elem['tval'];
} else {
$result[$key] = $elem;
}
}
$result = array_merge($result);
var_dump($result);
gives a result of:
array
0 =>
array
'id' => int 3
'title' => string 'book' (length=4)
'tval' => string '10000,1700' (length=10)
1 =>
array
'id' => int 27
'bcalias' => string 'fruit' (length=5)
'tval' => int 3000
The only real difference is the array_merge() to reset the keys

Categories