get value of an element inside an associative array from a table - php

$arr = ['b1' => 'banners/5B5C4965B9A50.jpg', 'vid' => 'vid.mp4', 'linked' => 'linkedabc'];
I inserted the above array into a table (using json_encode) so the content of the filed named map is:
{"b1":"banners/5B5C4965B9A50.jpg","vid":"vid.mp4","linked":"linkedabc"}
Now I want to get and loop this array:
$sql = "select map from params where what = 'artb'";
$st = $db->prepare($sql);
$st->execute();
$arrx = $st->fetch();
//$arrx = json_decode($arrx); - also tried here
foreach($arrx as $key => $el){
if($key == 'b1') {getb1($el);}
}
function getb1($el){
echo $el;
}
Result:
{"b1":"banners/5B5C4965B9A50.jpg","vid":"vid.mp4","linked":"linkedabc"}
I'm expecting banners/5B5C4965B9A50.jpg.
What's wrong?

$arrx = json_decode($arrx,true);
foreach($arrx as $key => $el){
if($key == 'b1') {getb1($el);}
}
You need an array before you loop it. You try to access a json object the way you access array which is not possible.
Your code will work perfect after that.
$data = '{"b1":"banners/5B5C4965B9A50.jpg","vid":"vid.mp4","linked":"linkedabc"}';
$arrx = json_decode($data,true);
foreach($arrx as $key => $el){
if($key == 'b1') {getb1($el);}
}
function getb1($el){
echo $el;
}
And the output is banners/5B5C4965B9A50.jpg as expected

Do json_decode first and then access the key directly.
$arrx = json_decode($arrx['map']);
To access b1,
echo $arrx->b1;
Your updated code snippet will look like this,
$sql = "select map from params where what = 'artb'";
$st = $db->prepare($sql);
$st->execute();
$arrx = $st->fetch();
foreach($arrx as $key => $el){
$elMap = json_decode($el['map']);
echo $elMap->b1;
}

Related

How to get data from database that result as an array in model codeigniter

I want to make a query that results like this in codeigniter MODEL:
$caldata = array (
15 => 'yes',
17 => 'no'
);
Is that possible to do?
Take NOTE: The 15,17 and yes,no are in the same database table.
There is no core helper function to achieve what you want in CI. But you can create your own helper function:
function pluck($arr = [], $val = '', $key = '')
{
// val - label for value in array
// key - label for key in array
$result = [];
foreach ($arr as $value) {
if(!empty($key)){
$result[$value[$key]] = $value[$val];
}else{
$result[] = $value[$val];
}
}
return $result;
}
you can use result_array() function so you can have something like:
$query = $this->db->select('id,answer')->from('users')->get();
$result = $query->result_array();
print_r($result);
After that you have your array and you can make the $key => $value relation of the fields
After a long search i found an answer. Sample way to do this:
$query = $this->db->select('start_date, class')->from('event')->like('start_date', "$year-$month", 'after')->get();
$datavariable = $query->result();
$caldata = array();
foreach($datavariable as $row){
$caldata[substr($row->start_date,8,2)] = $row->class;
}

How to extract data from JSON - Laravel & JSON

This is how my json looks like ["Chicken",{"quantity":"1"},"Froggies",{"quantity":"2"},"Fryies",{"quantity":"3"}].
Is there a way that i can get the data out the results like
Chicken : 1, Froggies:2, Fryies:3
I tried to use implode to get this done but i get an error saying array to string conversion,
Below is my code
foreach($request->get('item_id') as $key => $id)
{
$selected_item = Item::all()->where('id',$id);
foreach($selected_food as $select)
{
$food_selected[]= $select->name ;
$food_selected[] = ['quantity' => $request->get('quantity')[$key]];
}
}
$query ="Your items are ".implode(',',$food_selected)."";
Maybe array of objects would be more useful in that situation, which you could get this way:
$arr = [];
foreach ( $request->get('item_id') as $key => $id ) {
$selected_item = Item::all()->where('id', $id);
foreach ( $selected_item as $select ) {// $selected_item or $selected_food here
/*
$obj = new stdClass;
$obj->{$select->name} = $request->get('quantity')[$key];
$arr[] = $obj;*/
$arr[$select->name] = (int) $request->get('quantity')[$key];
}
}
$query = '';
foreach ( $arr as $k => $v ) {
$query .= ' '.$k.': '.$v.',';
}
$query = rtrim($query, ',');
$query = ltrim($query);
$query = "Your items are ".$query;
I assume that the ID is unique key for an Item and your Item::all()->where('id',$id) will return only one record. If this is true, the second loop is unnecessary.
Based on this assumption, I come to this code:
$result = collect($request->get('item_id'))
->map(function($itemId, $itemKey) use ($request) {
$item = Item::find($itemId);
return $item->name . ' : ' . $request->get('quantity')[$itemKey];
})->implode(',');
// $result contains the string: "Chicken : 2, Fries : 1"
For explanation:
Cast the array into a collection
Use map to loop over it
Find the Item by its ID
Return the name and the quantity (this returns a collection)
Implode the collection

PHP - Find Specific Value in Array (multidimensional)

I have the an array, in which I store one value from the database like this:
$stmt = $dbh->prepare("SELECT token FROM advertisement_clicks WHERE (username=:username OR ip=:ipcheck)");
$stmt->bindParam(":username",$userdata["username"]);
$stmt->bindParam(":ipcheck",$ipcheck);
$stmt->execute();
$data = array();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
So, that gives me: array("token","token");
When I print it:
Array ( [0] => Array ( [token] => 677E2114AA26BA4351A686917652C7E1BA67A32D ) [1] => Array ( [token] => C42190F3D72C5BB6BB6B68488D1D4662A8D2A138 ) )
I then have a loop, that loops all the tokens. In that loop, I try to search for a specific token, and if it that token matches, it will be marked as "seen":
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return $key;
}
}
}
This is my loop:
$icon = "not-seen";
foreach($d as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam == $token){
$icon = "seen";
}
}
However, searchForid() simply returns 0
What am I doing wrong?
Ok, here you can see a PHP fiddle that works
$data = array();
$data[] = array('token'=>'123');
$data[] = array('token'=>'456');
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return true;
}
}
return false;
}
$icon = "not-seen";
foreach($data as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam){
$icon = "seen";
}
}
echo $icon;
It echos 'seen' which is expected since I compare the same array values, now assuming that your $d variable has different tokens, it should still work this way.
That means that your $d array does not contain what you claim it contains, could you print_r this variable and post it in your answer?

Dynamic Array with PHP

Post Updated
I would like to create dynamic Array in PHP to provide the same output like static Array below, I have tried to do it with while statement but it doesn't work. Could you please provide me some tips?
I would like to use 2 values from MySQL and save them in to $to variable
so first send_to1 (user account) and then value1 (amount)
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM users");
$to=Array(
while($row = mysqli_fetch_array($result))
{
$send_to1 => $value1,
$send_to2=> $value2
}
);
mysqli_close($con);
?>
It's as simple as just adding elements to the array:
//Setup blank array
$example = array();
//Create a loop, for example purposes.
foreach(range(0, 99) as $i){
//Create random variable that we'll add to our array
$randVar = mt_rand(1, 90000);
//$i will be our array key/index
$example[$i] = randVar;
}
//var_dump the array so you can see the structure / end result
var_dump($example);
You could also create it like so:
//Create random array key/index
$myRandKey = mt_rand(1, 90000);
//Create random variable value.
$myRandVar = mt_rand(1, 90000);
//Setup an array
$example = array(
$myRandKey => $myRandVar
);
//Another array key that we'll add to our array
$secondKey = 'test';
//Add it
$example[$secondKey] = 'This is just an example!';
//Dump out the array
var_dump($example);
array_push will also work (using mysql_fetch_assoc, like in your example):
$example = array();
while($row = mysql_fetch_assoc($result)){
array_push($example, $row);
}
var_dump($example);
In your particular example (since you added your code):
print_r($new_array[] = $row[]);
should be changed to:
print_r($new_array[] = $row);
In your code, I'd change it to:
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[] = $row;
}
Or, if you want to key your array by a unique column (Primary key, for example):
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[$row['id']] = $row;
}
Look, this is so easy, you just need to pay more attention to the answers you're getting here.
Here is the simplest way you can do it:
$to = array();
$to[] = array($send_to1 => $value1);
$to[] = array($send_to2 => $value2);
while ( $row = mysqli_fetch_array($result) ) {
$to[] = array($row['send_tox' => $row['valuex']);
}
You need to first understand how Arrays and Loops work in PHP, then try to make a dynamic array in a loop.
Actually you almost got it. It's lower A in 'array'
To initialize an empty array:
$to = array();
In your case (you already have some values), you can do:
$to = array(
$send_to1 => $value1,
$send_to2=> $value2
);
In either case, you can later add more elements doing
$to[$someOtherKey] = $someOtherValue;

array to string php

Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";

Categories