get the specified outpot using php 2d array - php

I have got a 2d array called $myarray, and when I using var_dump($myarray), it gives me the following:
array(4) { [0]=> array(2) { [0]=> string(3) "EUR" [1]=> string(9) "43,543.23" } [1]=> array(2) { [0]=> string(3) "USD" [1]=> string(9) "13,432.34" } [2]=> array(2) { [0]=> string(3) "GBP" [1]=> string(8) "3,432.21" } [3]=> array(2) { [0]=> string(3) "CAD" [1]=> string(8) "2,321.34" } }
But I want the output to be the follwing format:
Totals
GBP 3,432.21
USD 13,432.34
EUR 43,543.23
CAD 2,321.34
I assume that I need to sort the array to be:
GBP 3,432.21
USD 13,432.34
EUR 43,543.23
CAD 2,321.34
and add "Totals", "" into the array, I might be wrong, soanybody could help me with that, any help will be greatly appreciated! I want it to be done in a programmatic way! how to sort the array $myarray to the expected output?

You're almost right.
Don't add the 'Totals' into the array. It is not data, mere decoration. For the rest, I wouldn't 'dump' the array, but e.g. for a string from it. As a rule, don't change your data especially for output formatting reasons, you'll find yourself removing the 'Totals' entry in the next function processing the data...:
Also, you want to control the iteration order; therefore you can iterate over the desired keys instead of over the array itself:
$output="Totals:\n";
foreach( $currency in array("GBP","USD","EUR","CAD") ) {
$entry=$data[$currency];
$output.=$currency." ".$entry[1]."\n";
}
dump($output);
EDIT - added the bit about ordering

Firstly, do not add anything non-data related to your array. You the string "Totals" should not be included in your array. If you just want the output, I suggest a better way to solve your problem :
<?php
class MyMoney {
var $type;
var $value;
public function __toString() {
return $type." ".$value."\n";
}
}
$output="Totals:\n";
// $data is an array of MyMoney objects
foreach( $entry in $data ) {
$output.= (string) $entry;
}
dump($output);
I hope this helps.

I'm not sure if this is what you're describing but perhaps it can be of use in your situation:
$myArray = array(
"title" => "Totals",
"data" => array(
"GBP" => "3,432.21",
"USD" => "13,432.34",
"EUR" => "43,543.23",
"CAD" => "2,321.34"
)
);
var_dump($myArray);
Output:
array(2) {
["title"]=>
string(6) "Totals"
["data"]=>
array(4) {
["GBP"]=>
string(8) "3,432.21"
["USD"]=>
string(9) "13,432.34"
["EUR"]=>
string(9) "43,543.23"
["CAD"]=>
string(8) "2,321.34"
}
}

<?php
$output = "Totals<br>";
foreach ($myarray as $value)
{
$output .= $value[0].' '.$value[1].'<br>';
}
echo $output;
?>

Related

Retrieving array key from value

I have the following array structure:
$this->entity += [
$key => [
'column' => $column,
'required' => $required,
'type' => $type,
'value' => $value,
'valueIfNull' => $valueIfNull,
'useDBDefaultWhenNull' => $useDBDefaultWhenNull
]
];
var_dump($this->entity);
array(13) {
["id"]=>
array(6) {
["column"]=>
string(2) "fk_tbl_users_id"
["required"]=>
bool(false)
["type"]=>
array(2) {
[0]=>
string(7) "integer"
[1]=>
int(1)
}
["value"]=>
string(0) ""
["valueIfNull"]=>
string(0) ""
["useDBDefaultWhenNull"]=>
bool(true)
}
["isAdmin"]=>
array(6) {
....
}
}
I need to be able to find the $key from a given $column value. I've tried the following, but of course, doesn't work:
$entity_key = array_search('fk_tbl_users_id', $this->entity, true);
I've also tried to make my $entity array with this structure (ommiting the keys 'column' etc):
$this->entity += [
$key => [
$column,
$required,
$type,
$value,
$valueIfNull,
$useDBDefaultWhenNull
]
];
var_dump($this->entity);
array(13) {
["id"]=>
array(6) {
[0]=>
string(2) "fk_tbl_users_id"
[1]=>
bool(false)
[2]=>
array(2) {
[0]=>
string(7) "integer"
[1]=>
int(1)
}
[3]=>
string(0) ""
[4]=>
string(0) ""
[5]=>
bool(true)
}
["isAdmin"]=>
array(6) {
....
}
}
Am I doing something wrong? I am assuming not, and the ONLY way I'll be able to retrieve the key is by force looping my array, get the 'column' value, compare it against a $col value, if true, then keep the $key and break my loop. Something like this:
private function getKeyname(string $col)
{
foreach ( $this->entity as $key => $value )
{
$key_colname = $value[0]; // or $value['column'], depending on array structure I end up using
if ( $key_colname === $col ) return $key;
}
}
I would of preferred not having to loop my array and use PHP builtin functions, if at all possible?
Thanks for your inputs!!
Pat.
Any type of multidimensional array search would use loops to search through,wheather you do it with a built-in function or a custom one.For this there are answers present at this resource PHP multidimensional array search by value.
Thanks for your replies folks! I went ahead and did my getKeyname() function. As a few mentioned, in the end buildin php functions still do loops anyhow ;)
Cheers! Pat

Add array to array without key IDs? - PHP

I have a big array which looks like this:
array(2) {
["Final Fantasy VII"]=>
array(5) {
["rows"]=>
array(2) {
[0]=>
array(6) {
["price"]=>
string(5) "11.69"
["price_old"]=>
string(4) "4.66"
["currency"]=>
string(4) "euro"
["portal"]=>
string(0) ""
["link"]=>
string(77) "https://de.gamesplanet.com/game/final-fantasy-vii-download--1001-1?ref=gmkeys"
["shop"]=>
string(4) "9507"
}
[1]=>
array(6) {
["price"]=>
string(5) "14.99"
["price_old"]=>
...
}
}
}
["Battlefield 1"]=>
array(3) {
["rows"]=>
array(2) {
[0]=>
array(6) {
["price"]=>
...
}
[1]=>
array(6) {
["price"]=>
...
}
}
}
}
And I want to get only certain parts of this array where the name is matching my searched title. So, I use this code for that:
function createACFRepeater($title){
$repeater = array();
if(searchForGameXML($title)){
$count = count($GLOBALS["productsXML"][$title]['rows']);
for($i = 0; $i < $count; $i++){
array_push($repeater, $GLOBALS["productsXML"][$title]['rows'][$i]);
}
return $repeater;
}else{
return $repeater;
}
}
My problem now is that the the $repeater array looks like this:
array(2) {
[0]=>
array(6) {
["price"]=>
string(5) "19.98"
["price_old"]=>
...
}
[1]=>
array(6) {
["price"]=>
string(4) "7.99"
["price_old"]=>
...
}
}
There is a numeric key which is pointing to the array [0] => .... But what I want is simply an array in a array without any associative relations...
How can I create an array which looks like this:?
array(2) {
array(6) {
["price"]=>
string(5) "19.98"
["price_old"]=>
...
}
array(6) {
["price"]=>
string(4) "7.99"
["price_old"]=>
...
}
}
Greetings and Thank You!
According to the array definition it is impossible. Any array item must have key and value, documentation for array starts from:
An array in PHP is actually an ordered map. A map is a type that associates values to keys
You will always have numeric keys. As #lubart already said: it's impossible to have an array without keys. Btw., all of the the follwing arrays are completely equal:
$array1 = array([0] => array([0] => 'hi', [1] => array([0] => '23.5')));
$array2 = array(array('hi', array('23.5')));
$array3 = [['hi', ['23.5']]];
$array4 = [ [0] => [ [0] => 'hi', [1] => [ [0] => '23.5' ] ] ];

How to loop through array of objects in PHP

I'm very new to PHP and I need your help!
I need to write backend for my app that receives json post and write data to json file. And I'm stuck with looping through array.
$postData = file_get_contents("php://input");
$request = json_decode($postData);
var_damp($request)
shows array:
array(2) {
[0]=>
object(stdClass)#1 (8) {
["name"]=>
string(11) "Alex Jordan"
["email"]=>
string(14) "alex#gmail.com"
["phone"]=>
int(123456789)
["street"]=>
string(12) "street, str."
["city"]=>
string(7) "Chicago"
["state"]=>
string(7) "Chicago"
["zip"]=>
string(5) "07202"
["$$hashKey"]=>
string(8) "object:3"
}
[1]=>
object(stdClass)#2 (8) {
["name"]=>
string(15) "Michael Jonhson"
["email"]=>
string(17) "michael#gmail.com"
["phone"]=>
float(11987654321)
["street"]=>
string(12) "street, str."
["city"]=>
string(11) "Los Angeles"
["state"]=>
string(10) "California"
["zip"]=>
string(5) "27222"
["$$hashKey"]=>
string(8) "object:4"
}
}
I'm trying to loop through the objects and getting error
Object of class stdClass could not be converted to string
Here is how I'm trying to do it:
foreach($request as $i => $i_value) {
echo $i_value;
}
$i_value is the object. Because it's an object you cannot just echo it (unlike in JavaScript where you can cast any object to string).
You can echo specific properties of the object:
foreach($request as $i => $i_value) {
echo $i_value->name;
}
Of course you could also use var_dump again to dump each object. print_r should work too.
Objects can only be casted to string like you do if they implement the __toString() magic method, but the objects created by json_decode are just simple StdClass objects that do not implement this. It's probably not your intention to do this at all, but if you're curious, you may have a look at json_decode to custom class to see how you may use a custom class instead of StdClass.
I had the same problem recently. I used a for loop to loop through the array which gave me an error of undefined offset. Using isset() solved the error of undefined offset. I know its too late to answer this question but here it is for someone who might be looking for it in future
$postData = file_get_contents("php://input");
$request = json_decode($postData);
// or you can do $postData = json_decode(file_get_contents("php://input"));
$arrayOfUsers = $request->data; // I used a key of data while sending the array via fetch API
for($x = 0; $x < count($arrayOfUsers); $x++)
{
if(isset($arrayOfUsers[$x]))
{
$name = $arrayOfUsers[$x]->name;
$email = $arrayOfUsers[$x]->email;
$phone = $arrayOfUsers[$x]->phone;
$street = $arrayOfUSers[$x]->street;
// .... and so on
// then you can do whatever you want with the data
} else {
echo "No Data Found";
}
}
You can also use array_map(?callable $callback, array $array, array ...$arrays): array
to get required properties of each object;
or even alter its data.
This code covers both cases (sandbox_url):
<?php
$arr_of_objects[] = (object)['field_name' => 'test2', 'id' => 2];
$arr_of_objects[] = (object)['field_name' => 'test', 'id' => 1];
$array_of_names = array_map(function ($el) {
return $el->field_name;
}, $arr_of_objects);
echo 'get field_name from array of objects' . "\n";
var_dump($array_of_names);
$replace_data_with = [
1 => ['field_name' => 'replaced_name_1', 'id' => 777],
2 => ['field_name' => 'replaced_name_2', 'id' => 999]
];
$changed_values = array_map(function ($el) use ($replace_data_with) {
$el->field_name = $replace_data_with[$el->id]['field_name'];
$el->id = $replace_data_with[$el->id]['id'];
return $el;
}, $arr_of_objects);
echo 'alter data of each object' . "\n";
var_dump($changed_values);
Base array of Objects:
array(2) {
[0]=>
object(stdClass)#1 (2) {
["field_name"]=>
string(5) "test2"
["id"]=>
int(2)
}
[1]=>
object(stdClass)#2 (2) {
["field_name"]=>
string(4) "test"
["id"]=>
int(1)
}
}
Output:
get field_name from array of objects
array(2) {
[0]=>
string(5) "test2"
[1]=>
string(4) "test"
}
alter data of each object
array(2) {
[0]=>
object(stdClass)#1 (2) {
["field_name"]=>
string(15) "replaced_name_2"
["id"]=>
int(999)
}
[1]=>
object(stdClass)#2 (2) {
["field_name"]=>
string(15) "replaced_name_1"
["id"]=>
int(777)
}
}

Sort an array from another array values in PHP

I got an $actions array, and $actions_used array.
$actions_used looks like this:
array(1) {
[2]=>
string(1) "18"
[5]=>
string(1) "33"
}
$actions looks like this:
array(3) {
[1]=>
string(9) "Withdraw"
[2]=>
string(13) "Deposit"
[5]=>
string(10) "Blabla"
}
I would like to sort $actions based on the value that is in $actions_used.
The correct output would be for $actions:
array(3) {
[5]=>
string(9) "Blabla"
[2]=>
string(13) "Deposit"
[1]=>
string(10) "Withdraw"
}
Why? Because array key 5, "Blabla" has the biggest value "33" and then comes array key "2" which has value 18 and then at last comes array key 1, "Withdraw" which have 0 (no value)
How can this be done?
This should do the trick.
$sorted_actions = array();
asort($actions_used);
foreach($actions_used AS $key => $amount) {
$sorted_actions[] = array('amount' => $amount, 'action' => $actions[$key]);
unset($actions[$key]);
}
$sorted_actions = $sorted_actions + $actions;
How would something like this work?
arsort($action_used);
foreach ($action_used as $k => $v) {
$newArray[$k] = $actions[$k];
unset($action_used[$k];
}
$newArray = array_merge($newArray, $action_used);
I think you could sort the second array with uksort and actually compare the values from the first array in the custom comparer
e.g.:
uksort($arr2, function($i1, $i2) {
return $arr1[$i1] - $arr1[$i2];
});

sort the array and remove part of it afterwards

I have a 2d array called $myarray and I use var_dump($myarray), it gives me the following:
array(4) {
[0]=> array(3) {
[0]=> string(11) "PAY000003RV"
[1]=> string(3) "EUR"
[2] => string(9) "43,543.23"
}
[1]=> array(3) {
[0]=> string(11) "PAY000002PE"
[1]=> string (3) "USD"
[2]=> string(9) "13,432.34"
} [2]=> array(3) {
[0]=> string(11) "PAY000001YB"
[1] => string(3) "GBP"
[2]=> string(8) "3,432.21"
} [3]=> array(3) {
[0]=> string(11) "PAY000004TS"
[1]=> string(3) "CAD"
[2]=> string(8) "2,321.34"
}
}
I want to get the following output:
GBP 3,432.21
USD 13,432.34
EUR 43,543.23
CAD 2,321.34
so I try to use substr($myarray[0][0], 8, 1), substr($myarray[1][0], 8, 1), substr($myarray[2][0], 8, 1), substr($myarray[3][0], 8, 1) to get the value 3,2,1,4 in order to use it to sort the array to the above order and then delete $myarray[0][0], $myarray[1][0], $myarray[2][0], $myarray[3][0] which are the "PAY0000.." elements in every row, but I am not sure how exactly to implement that, any experts could help me with that? any help will be greatly appreciated!
//Extract sort key
$tmp=array();
foreach($myarray as $m) $tmp[$m[0]]=array($m[1],$m[2]);
//Sort array
ksort($tmp);
//Create output
foreach($tmp as $m) echo $m[0].' '.$m[1];
Some comments:
You can sort by PAY00000nXY without extracting n
The code assumes you need the array for more than printing it out, else it might be inefficient
Let's say your array is assigned to variable $foo
$values = array();
foreach ( $foo as $bar ) {
foreach ( $bar as $val ) {
$values[] = $val[1] . ' ' . $val[2];
}
}
Then you will have the array $values with the values you need.

Categories