Retrieving array key from value - php

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

Related

Combing matched keys in an array

Edited
I get the combined item_ids now, but not the single item_ids.
I have an array with three keys.
$searchArray = {
[0]=> array(3) {
["keyword"]=> string(7) "history"
["url"]=> string(7) "history"
["item_id"]=> string(2) "16"
}
[1]=> array(3) {
["keyword"]=> string(4) "past"
["url"]=> string(4) "past"
["item_id"]=> string(2) "16"
}
[89]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "34"
}
[93]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "35"
}
I want to combine the options that have the same keyword/url.
Just need to check if keyword matches.
The final format needs to be something that jquery autocomplete can accept, where I can assign the text to keyword and the value to url, id to the item_id.
There were only two keys in the array before and I would combine matches this way.
foreach ($searchArray as $row)
{
$combineMatches[ $row['keyword'] ][] = $row['item_id'];
}
result after using json_encode():
"anthropologist":["27","37"],
"biomedical":["34","35"],
"m.s.":["18","19","23"]
What I currently have:
$combineMatches = array();
foreach ($searchArray as $row)
{
$match =
array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id']+= $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array_push($row['item_id'])
]);
}
}
Result:
[7]=> array(3)
{
["keyword"]=> string(8) "theology"
["url"]=> string(8) "theology"
["item_id"]=> NULL
}
[13]=> array(3)
{
["keyword"]=> string(7) "writing"
["url"]=> string(7) "writing"
["item_id"]=> NULL
}
How do I add to the array column of just item_id ? Which I see is a string, but I need as an array.
This gets JSON encoded in the end of the PHP and read by jquery autocomplete.
Thank you for pointing out the string/array issue.
I changed how to add to the third key if there is a match, and if there isn't a match the solution was changing the array_push to just array.
$combineMatches = array();
foreach ($searchArray as $row)
{
$match=array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id'][] = $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array($row['item_id'])
]);
}
}

PHP Object giving values to a string from a mysqli_fetch_array

public static function instantiate($record){
$object = new self;
// $object->id = $record['UserID'];
// $object->username = $record['Username'];
// $object->password = $record['Password'];
// $object->first_name = $record['Fname'];
// $object->last_name = $record['Lname'];
// $object->email = $record['Email'];
foreach (array_unique($record) as $attribute => $value) {
if($object->has_attribute($attribute)){
$object->$attribute = $value;
//var_dump($attribute);echo '<br>';
}
}
return $object;
}
In this function i get values from this $object in two ways. The long way from the commented part and the short way from the uncommented (obv).
The long way gives the good result as this :
object(User)#5 (6) { ["id"]=> string(1) "1" ["username"]=> string(6) "Parley" ["password"]=> string(5) "12345" ["first_name"]=> string(8) "Cristian" ["last_name"]=> string(8) "Pirloaga" ["email"]=> string(27) "cristian.pirloaga#gmail.com" }
The short way gives a bad result as this :
int(0)
int(1)
int(2)
int(3)
int(4)
int(5)
int(6)
object(User)#5 (13) { ["id"]=> NULL ["username"]=> NULL ["password"]=> NULL ["first_name"]=> NULL ["last_name"]=> NULL ["email"]=> NULL ["0"]=> string(1) "1" ["1"]=> string(8) "Cristian" ["2"]=> string(8) "Pirloaga" ["3"]=> string(27) "cristian.pirloaga#gmail.com" ["4"]=> string(6) "Parley" ["5"]=> string(5) "12345" ["6"]=> string(19) "2016-02-12 05:04:22" }
the int(1)..int(6) are the $attribute values, after is the object.
Im trying to match the $attribute values with those fields from the long way. How can i do it?
This is an actually code from a tutorial and it works to him and not to me.
I have a secondary issue. The foreach loop always double the values.In this case if i remove the array_unique function it will show that result two times tho in data base its only one row.why's that?
You can have the result you want by using mysqli_fetch_object instead of mysqli_fetch_array.
But to answer your question: If you use mysqli_fetch_array, by default you get an array containing numeric keys and associative keys as well. For example something like:
array(
1 => 'john',
2 => 'doe',
'firstname' => 'john',
'lastname' => 'doe'
)
To avoid that you can set the third parameter int $result_type to MYSQL_ASSOC as described here:
http://php.net/manual/de/function.mysql-fetch-array.php
Using MYSQL_ASSOC you will get an array without numeric keys, for example:
array(
'firstname' => 'john',
'lastname' => 'doe'
)
Doing that your function will work, even without the array_unique in the foreach.

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];
});

get the specified outpot using php 2d array

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;
?>

Categories