PHP - fetch value of specified key pair in mulit-dimensional array - php

hopefully a easy one for you,
my sql query is returning a mulit-dimensional array, I need to access only one key the is nested on the second level but cant figure out how.
here is my function.
public function get_visitor_id($id)
{
$this->db->where('mobile',$id);
$this->db->or_where('email',$id);
$this->db->select('uid');
$result = $this->db->get('visitors');
if ($result)
{
foreach ($result->result() as $key=>$value){
$array[$key] = $value;
}
var_dump($array);
return $array;
}
}
The array returned is
{ [0]=> object(stdClass)#20 (1) { ["uid"]=> string(2) "24" } }
I only need the value of ['uid'] so in essence if I was to echo get_visitor_id() it would evaluate to "24".
Thanks for you help.
Cheers

try changing foreach() func to:
foreach($result as $res){
$res = $res->fetch_assoc();
$array['uid'] = $res['uid'];}
EDIT: in case of this didn't work then try while loop:
while($res = $result->fetch_assoc()){
$array['uid'] = $res['uid'];
}

Related

get array from an array of array using value

I have an array of array like this
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
I have value 9908. When I search 9908 then the value array("9908","1","5") should be printed. I have used array_search() but I have not got any success
How I can print the array after finding the value
Try this:
var_dump($data[array_search("9908", array_column($data, 0))]);
To expand it,
array_column returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.
array_search Searches the array for a given value and returns the first corresponding key if successful.
Edit:
To add some control over it:
$index = array_search("9908", array_column($data, 0));
if($index !== false){
// do your stuff with $data[$index];
var_dump($data[$index]);
}
Dumps:
array(3) {
[0]=>
string(4) "9908"
[1]=>
string(1) "1"
[2]=>
string(1) "5"
}
Perhaps this can help:
<?php
function search_first_row($needle, $haystack){
$data = $haystack;
$desired_value = $needle;
foreach($data as $row){
if($row[0] == $desired_value){
return $row;
}
}
}
try this :
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
foreach ($data as $key => $value) {
if( in_array("9908",$value)){
$findindex = $key;
}
}
var_dump($data[$findindex]);
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
$searchValue = '9908';
for($i=0; $i<count($data); $i++){
$innerArray = $data[$i];
for($j=0; $j<count($innerArray); $j++){
if($innerArray[$j] == $searchValue){
print_r($innerArray);
}
}
}

PHP Accessing mysqli_fetch_assoc value

I have been trying to store the results of a MySQL query in a PHP array, however I have been struggling to access the values after they have been stored.
I used this to store the query:
while($row = mysqli_fetch_assoc($result)) {
array_push($array, $row);
}
Which when showing the array with var_dump gives an output similar to this, just with more values:
array(147) { [0]=> array(1) { ["TABLE_NAME"]=> string(8) "_3085515" } }
I want to be able to access the value with the _NUMBER, but I can't figure out how to do this?
1st : Declare the variable as a array
$array = array();
while($row = mysqli_fetch_assoc($result)) {
array_push($array, $row);
}
2nd : Access the value like this
$array[0]['TABLE_NAME']
Do like that.
$array = [];
while($row = mysqli_fetch_assoc($result)) {
array_push($array, $row);
}

Laravel 5.4: how to iterate through request array?

My request data represents an array of new and existing items. I'm trying to through this array to update and create items.
This is how I retrieve the array:
$userInput = $request->all();
foreach( $userInput['items'] as $key=>&$item){
Later in the code I update an existing item:
$updateItem = Item::find($item['id']);
$updateItem->number = $item['number'];
$updateItem->save();
But $item['number'] seems to contain old input from previous updates and not the value I entered last time.
How can I loop through request data in Laravel ?
This is the whole code as I run it (want to get rid of confusion):
$userInput = $request->all();
// checking $userInput here
// I can see the new value in the array
foreach( $userInput['items'] as $key=>$item){
if($item['delete'] == 1) {
Item::where('order_id',$order->id)
->where('id',$item['id'])
->delete();
} else {
if(empty($item['id'])) {
} else {
$updateItem = Item::find($item['id']);
$updateItem->number = $item['id'];
$updateItem->save();
}
}
}
This is an input from html (just to show I checked the form also, the data comes just fine):
<input id="basicItemNumber-31" class="form-control" name="items[31][number]" placeholder="Unique number" value="31" type="text">
It's likely that somewhere inside your for you've inadvertently changed the value of your underling $item as you pass it by reference (using the & before the variable name.)
It's considered bad practice by some or most people as it can lead to "unexpected" behaviour, For example. take the sample code below that loops through an array of $items twice once by reference and once by value.
<?php
$items = ['one','two','three'];
foreach ($items as &$item) {
//do nothing.
}
foreach ($items as $item) {
//do nothing again.
}
var_dump($items);
//outputs
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
&string(3) "two"
}
Try something like this as it will keep your scope local:
$request['items']->each(function($item, $key) use ($order) {
if ($item->delete) {
Item::where('order_id',$order->id)
->where('id',$item['id'])
->delete();
} else {
if (!empty($item['id'])) {
$updateItem = Item::find($item['id']);
$updateItem->number = $item['id'];
$updateItem->save();
}
}
});

array_search() in Session Array

I tried to use the function array_search but can't get it work..
I got a php session with an array.
array(2) {
[0]=>
array(6) {
["ProductId"]=>string(2) "34"
["ProductName"]=>string(9) "Best ever"
["ProductPrice"]=>string(6) "453.00"
["ProductColor"]=>string(4) "Blue"
["ProductSize"]=>string(1) "S"
["Image"]=>string(36) "d12f95895c9130da8e52a7ff5b9216c9.png"
}
[1]=>
array(6) {
["ProductId"]=>string(2) "33"
["ProductName"]=>string(5) "Vespa"
["ProductPrice"]=>string(7) "1789.00"
["ProductColor"]=>string(4) "Blue"
["ProductSize"]=>string(1) "S"
["Image"]=>string(36) "678e25ea94a7fa94bc6fa427ff29bc6c.png"
}
now I do an array_search()
session_start();
include '_sqlclean.php';
(isset($_POST['product_id'])) ? $p_id = clean_string_save($_POST['product_id']) : $p_id = 0;
$array = $_SESSION['wishList'];
$key = array_search($p_id, $array);
if I do a
var_dump($_SESSION['wishList']);
I got what I showed you above.
But I always got the message "Key not found"
Why ?? What's my mistake ?
I tried already to do
$p_id = "34" // for try
$p_id = intval(34); // for try also
$key = array_search("34", $_SESSION['wishList']); // to see if it works
but nothing worked.. :(
Thanks in advance
array_search will not work for multidimensional arrays. Rather this might work -
$key = array_search($p_id, array_column($array, 'ProductId'));
This will extract all the ProductId from that array then do the search.
Try with alternative for array_search().For example:
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
OR
$key = array_search($p_id, array_column($array, 'ProductId'));
Aparently you are mistyping the variable (key) name
in the array it is
ProductId
and in your code it is
Product_Id
It happen cause you search into outer array, which contains only [0] and [1] keys.
Try to use
$key = array_search("34", $_SESSION['wishList'][1]);
You can try an alternative way like
<?php
$p_id = "34" // for try
$p_id = intval(34); // for try also
if(in_array($p_id, array_values($_SESSION['wishList']))) {
// Product Id found in your wishList
}
?>
It will works only for single dimension array. For multidimensional use foreach loop.

PHP unique array by value?

I have an array in PHP that looks like this:
[0]=>
array(2) {
["name"]=>
string(9) "My_item"
["url"]=>
string(24) "http://www.my-url.com/"
}
[1]=>
array(2) {
["name"]=>
string(9) "My_item"
["url"]=>
string(24) "http://www.my-url2.com/"
}
The two values in "name" are the same in this two items. I want to sort out duplicates like this.
How do I create an unique array by checking the "name" value?
basically
$unique_array = [];
foreach($your_array as $element) {
$hash = $element[field-that-should-be-unique];
$unique_array[$hash] = $element;
}
$result = array_values($unique_array);
Serialisation is very useful for simplifying the process of establishing the uniqueness of a hierarchical array. Use this one liner to retrieve an array containing only unique elements.
$unique = array_map("unserialize", array_unique(array_map("serialize", $input)));
Please find this link useful, uses md5 hash to examine the duplicates:
http://www.phpdevblog.net/2009/01/using-array-unique-with-multidimensional-arrays.html
Quick Glimpse:
/**
* Create Unique Arrays using an md5 hash
*
* #param array $array
* #return array
*/
function arrayUnique($array, $preserveKeys = false)
{
// Unique Array for return
$arrayRewrite = array();
// Array with the md5 hashes
$arrayHashes = array();
foreach($array as $key => $item) {
// Serialize the current element and create a md5 hash
$hash = md5(serialize($item));
// If the md5 didn't come up yet, add the element to
// to arrayRewrite, otherwise drop it
if (!isset($arrayHashes[$hash])) {
// Save the current element hash
$arrayHashes[$hash] = $hash;
// Add element to the unique Array
if ($preserveKeys) {
$arrayRewrite[$key] = $item;
} else {
$arrayRewrite[] = $item;
}
}
}
return $arrayRewrite;
}
$uniqueArray = arrayUnique($array);
var_dump($uniqueArray);
See the working example here:
http://codepad.org/9nCJwsvg
Simple Solution:
/**
* #param $array
* #param null $key
* #return array
*/
public static function unique($array,$key = null){
if(null === $key){
return array_unique($array);
}
$keys=[];
$ret = [];
foreach($array as $elem){
$arrayKey = (is_array($elem))?$elem[$key]:$elem->$key;
if(in_array($arrayKey,$keys)){
continue;
}
$ret[] = $elem;
array_push($keys,$arrayKey);
}
return $ret;
}
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$result = unique_multidim_array($visitors,'ip');
Given that the keys on the array (0,1) do not seem to be significant a simple solution would be to use the value of the element referenced by 'name' as the key for the outer array:
["My_item"]=>
array(2) {
["name"]=>
string(9) "My_item"
["url"]=>
string(24) "http://www.my-url.com/"
}
...and if there is only one value other than the 'name' why bother with a nested array at all?
["My_item"]=>"http://www.my-url.com/"

Categories