PHP Search Multi Dimensional Array [duplicate] - php

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 6 years ago.
I have two functions that I am working with. The first one does a database call and grabs two attributes of a user. The UserID and Markup for that user.
/*
Search Markup for a specific QID
*/
function searchMarkup($identifier){
global $markupArray;
if(isset($markupArray)){
foreach($markupArray as $m){
if((string)$key->QID == (string)$identifier){
return $m->markup;
}
}
}
return '';
}
/*
Fetch the markup data for this dashboard
*/
function fetchMarkup(){
global $dashboardID;
global $markupArray;
$objDB = new DB;
$objMarkup = $objDB
-> setStoredProc('FetchMarkup')
-> setParam('dashboardID', $dashboardID)
-> execStoredProc()
-> parseXML();
// Create an array of the markup
if(isset($objMarkup->data)){
$i = 0;
foreach($objMarkup->data as $m){
$markup[$i] = array();
$markup[$i]['QID'] = (string)$m->QID;
$markup[$i]['markup'] = (string)$m->Markup;
$i++;
}
$markupArray = $markup;
}
}
When I run fetchMarkup() and then print out $markupArray, I get the result of:
Array
(
[0] => Array
(
[QID] => Q0002
[markup] => success
)
[1] => Array
(
[QID] => Q101
[markup] => success
)
[2] => Array
(
[QID] => Q200
[markup] => info
)
)
My next step is to be able to search that array by providing a QID and having it return the markup value to me.
I am trying to so something like searchMarkup('Q0002') to have it tell me the result of markup but I am not getting any response.
How could I go about retrieving the value of markup from the array that is created by fetchMarkup() ?

why you are using $key ? which came from no where
foreach($markupArray as $m)
as you can see you alias $m not $key
And $markupArray is an associated array not an object array
So instead of
if((string)$key->QID == (string)$identifier){
return $m->markup;
}
since it is an associated array change it to
if((string)$key['QID'] == (string)$identifier){
return $m['markup'];
}
So your searchMarkup would be like this
function searchMarkup($identifier){
global $markupArray;
if(isset($markupArray)){
foreach($markupArray as $m){
if((string)$m['QID'] == (string)$identifier){
return $m['markup'];
}
}
}
return '';
}
Demo

Related

PHP - get value from JSON

Before i decode my JSON i get this result:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1},
"2":[{"membership_id":3,"group_id":1,"user_id":2}
}
How would i specify that i want to select the one who has 'user_id' == 2 and return membership_id value?
My attempt, but i get undefined value 'user_id':
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value['user_id'] == $cid){
$mid = $value['membership_id'];
}
}
echo $mid;
Basically i guess i would first have to select the right object and go through it with the foreach, but here i got a bit lost in the situation.
Use Array-Functions:
$json = '{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}';
$array = json_decode($json, true);
$searchUserID = 2;
$filteredArray = array_filter($array, function($elem) use ($searchUserID){
return $searchUserID == $elem[0]['user_id'];
});
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
echo "Membership-ID: ".$mid;
array_filter uses a callback function that iterates over every element of the array. If the callback function returns true, that element is assigned to $filteredArray. No need for a foreach loop that way.
But the return value is the whole array element:
Array
(
[2] => Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
)
So you have to extract your membership_id.
Read the following line from inside out.
First, we fetch the first entry of the array with array_shift (since we have only one entry, this will be our desired entry).
Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
We pass this array on to array_column to find the entry in the encapsulated array with the column name membership_id. Since array_column again returns an array,
Array
(
[0] => 3
)
we get the (one and only) entry by adding [0] to the end of this command.
Since the last part is a little complicated, here's a torn apart version of it:
$firstEntryOfFilteredArray = array_shift($filteredArray);
$arrayWithValueOfColumnMembershipID = array_column($firstEntryOfFilteredArray, 'membership_id');
$membership_id = $arryWithValueOfColumnMembershipID[0];
These three lines are concatenated into this:
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
here's a working example: http://sandbox.onlinephpfunctions.com/code/8fe6ede71ca1e09dc68b2f3bec51743b27bf5303
I'm assuming the JSON actually looks like:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}
Each element of the object is an array for some reason. So you need to index it with $value[0] to access the object contained inside it.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value[0]['user_id'] == $cid){
$mid = $value[0]['membership_id'];
break;
}
}
echo $mid;
If the arrays can contain multiple elements, you'll need nested loops.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
foreach ($value as $object) {
if($object['user_id'] == $cid){
$mid = $object['membership_id'];
break 2;
}
}
}
echo $mid;
This is a bit speculative, but I think the data is indexed by user ID. If that's the case, it makes the lookup much simpler.
After decoding with $myjson = json_decode($s_o, true);
Just find the record by ID and get the membership_id from the matching row.
$membership_id = reset($myjson['2'])['membership_id'];`
You should probably verify that that ID exists, so maybe something like:
$membership_id = isset($myjson['2']) ? reset($myjson['2'])['membership_id'] : null;
If I'm wrong and the fact that the row numbers match the user_id is just a coincidence, then never mind :)

How to muliply array values and store in third array variable in codeigniter

I have two array variables like this
$order_qty=array('1','2','3');
$quantity_per_pack= array('50','100','100')
I want to multiply these two variables and get stored in third variable which will be in array form such as
$total_order_qty = array('50','200','300')
This is my code:
for ($i=0;$i<10;$i++)
{
$total_order_qty[$i] = $quantity_per_pack[$i] * $order_qty[$i] ;
echo $total_order_qty[$i];
}
I declared these three variables as array before for loop.
Please help me to get solution for this.
Hope this will help your
you can use array_map for that like this
working demo :https://eval.in/1014627
function multi($n, $m)
{
return($n*$m);
}
$order_qty = array('1','2','3');
$quantity_per_pack = array('50','100','100');
$total_order_qty = array_map("multi", $order_qty, $quantity_per_pack);
print_r($total_order_qty );
Program Output
Array
(
[0] => 50
[1] => 200
[2] => 300
)
For more : http://php.net/manual/en/function.array-map.php

How to save this JSON stringified array into database? [duplicate]

This question already has answers here:
how to save json model object to php mysql database
(2 answers)
Closed 5 years ago.
I have a form that submitted a stringified JSON array. This is the data example:
"[{'name':'i_cp_nm','value':'1'},{'name':'i_cp_tp','value':'2'},{'name':'i_cp_mb','value':'3'},{'name':'i_cp_em','value':'4'},{'name':'i_cp_jb','value':'5'},{'name':'i_cp_nt','value':'6'},{'name':'i_cp_nm','value':'7'},{'name':'i_cp_tp','value':'8'},{'name':'i_cp_mb','value':'9'},{'name':'i_cp_em','value':'10'},{'name':'i_cp_jb','value':'11'},{'name':'i_cp_nt','value':'12'}]";
This is the desired inserted data looks like:
i_cp_jd i_cp_nm i_cp_tp i_cp_mb i_cp_em i_cp_jb i_cp_nt
xxx 1 2 3 4 5 6
xxx 7 8 9 10 11 12
This is the current loop, but I do not know if this is right:
$arr_cp = //arr_data
foreach($arr_cp as $val_cp){
$dt_cp['i_cp_jd'] = $this->input->post('i_v_id');
//didn't know what to do here
$this->model_vendor->insert_vendor_pic($dt_cp);
}
the the insert method:
function insert_vendor_pic($dt_cp){
$query = $this->db->insert('vendordetail_pic',$dt_cp);
return $query;
}
All you have to do is using json_decode:
$arr_cp = json_decode($yourJsonData, true);
Try this function for prepare/convert your input to matrix:
function prepareData($rawData) {
$rawData = str_replace("'", '"', $rawData);
$data = array();
foreach(json_decode($rawData, true) as $d) {
if (!isset($data[$d['name']])) {
$data[$d['name']] = array();
}
$data[$d['name']][] = $d['value'];
}
$rows = array();
foreach ($data as $col => $values) {
foreach ($values as $i => $v) {
if (!isset($rows[$i])) {
$rows[$i] = array();
}
$rows[$i][$col] = $v;
}
}
return $rows;
}
Convert:
$rawData = "[{'name':'i_cp_nm','value':'1'},{'name':'i_cp_tp','value':'2'},{'name':'i_cp_mb','value':'3'},{'name':'i_cp_em','value':'4'},{'name':'i_cp_jb','value':'5'},{'name':'i_cp_nt','value':'6'},{'name':'i_cp_nm','value':'7'},{'name':'i_cp_tp','value':'8'},{'name':'i_cp_mb','value':'9'},{'name':'i_cp_em','value':'10'},{'name':'i_cp_jb','value':'11'},{'name':'i_cp_nt','value':'12'}]";
print_r(prepareData($rawData));
Output:
Array
(
[0] => Array
(
[i_cp_nm] => 1
[i_cp_tp] => 2
[i_cp_mb] => 3
[i_cp_em] => 4
[i_cp_jb] => 5
[i_cp_nt] => 6
)
[1] => Array
(
[i_cp_nm] => 7
[i_cp_tp] => 8
[i_cp_mb] => 9
[i_cp_em] => 10
[i_cp_jb] => 11
[i_cp_nt] => 12
)
)
Finally you can simple insert this data to DB any way you like.
If you want to do it systematically then you should use an appropriate JSON parser/ deserializer to create an instance of the domain or whatever you are supposed to create from that form data and insert those instances in the DB.
If you want to do it systematically then you should use a appropriate JSON parser/ deserializer to create an instance of the domain or whatever you are supposed to create from that form data and insert that in DB.
The data in the json format, so you have to decode json into array by using
$arr_cp = json_decode($arr_cp, TRUE);
then do $arr_cp into foreach loop
foreach($arr_cp as $val_cp){
$dt_cp['i_cp_jd'] = $this->input->post('i_v_id');
//didn't know what to do here
$this->model_vendor->insert_vendor_pic($dt_cp);
}

Match array key with a string then add a function to the key value - php

I'm trying to compare a string with an array key and if they match, I want to call a function to replace the value of the matched key.
my array:
Array ( [id] => 1 [username] => Ahmed [name] => Ahmed Jalal [avatar] => no_avatar.png )
my function:
resizer($avatar,'50');
and I'm using this cod to do the job
$query = $db->prepare($mysql);
$db->stmt_assoc($query, $table);
$query->fetch();
if ($table['avatar']) {
$data[] = call_user_func('resizer', $table['avatar'],'50');
$table['avatar']=$data;
}
if($type == 'json'){
return json_encode($data);
}else{
return $table;
}
Ok sorry for my misunderstanding so here is some code based off the array you gave. It will turn each key into the name of a variable and store the value of that key in the named variable.
$g['id'] = 1;
$g['username'] = 'Ahmed';
$g['name'] = 'Ahmed Jalal';
$g['avatar'] = 'no_avatar.png';
foreach($g as $k => $v)
{
$$k = $v;
}
echo $avatar; // displays no_avatar.png
Yes you can use resize if you include the path to the image in avatar or in a new array key while using gd or imagemagick or another gfx addition to php.

PHP - in_array isn't finding my value [duplicate]

This question already has answers here:
in_array() and multidimensional array
(24 answers)
Closed 8 years ago.
I'm a newb and I got a problem with in_array...
So this is my array $allUsers (received by a SQL-Query for Usernames)
Array
(
[0] => Array
(
[name] => test
)
[1] => Array
(
[name] => test2
)
[2] => Array
(
[name] => admin
)
[3] => Array
(
[name] => kingChräbi
)
Now If a new member wants to register, I want to check in this array if it's already existent:
if(!in_array($username,$allUsers)){....
eventhough it is to when $username is NOT in $allUsers do .... it's just skipping to else also if the user is existing :(
$username is set before with
$username = $_POST['name'];
and working as it should (i can echo it without a problem, is exactly test or test2 without whitespace or anything)
I really looked around alot, but I can't find anything like my problem here... Could you please help me?
Thanks
although question itself is quite silly, as you have to realize what array you are working with, the quick solution, based on PDO tag, would be as follows: instead of fetchAll() use fetchAll(PDO::FETCH_COLUMN)
Or, rather you need to learn SQL as well, and find users not by means of selecting them ALL from database which makes no sense, but by asking a database to find a user for you
$stm = $pdo->prepare("SELECT * FROM table WHERE name=?");
$stm->execute(array($_POST['name']));
$user = $stm->fetch();
if ($user) { // <---HERE YOU GO
The in_array() does not work with multi-dimensional arrays. You better flatten your array and then do a search for the keyword.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)); //<-- Pass your array here
$new_arr = array();
foreach($it as $v) {
$new_arr[]=$v;
}
if(in_array('test',$new_arr))
{
echo "Exists !";
}
Working Demo
You are searching a 2-D array for a value under the key of "name".
Using array_map() or simple foreach loop should work -
$username = "admin";
$key = "name";
if(!in_array($username,array_map(function($v)use($key){return $v[$key];},$allUsers))){
echo "No found";
}else{
echo "Found";
}
If you are using:
While ($ row=mysql_fetch_assoc ($ result) {
$ data [] = $ row
}
Remove the [] to not create a multidimensional array.

Categories