I have an array of associative array, I will like to update the values in this array, hence I created a function that looks like this.
//The Array of Associative arrays
array (size=2)
0 =>
array (size=3)
'slang' => string 'Tight' (length=5)
'description' => string 'Means well done' (length=15)
'example-sentence' => string 'Prosper it Tight on that job' (length=28)
1 =>
array (size=3)
'slang' => string 'Sleet' (length=5)
'description' => string 'Means to send on long errand' (length=28)
'example-sentence' => string 'I am going to sleep sia' (length=23)
//The function
public function update($slang, $new)
{
array_map(function($data, $key) use($slang, $new)
{
if($data['slang'] == $slang)
{
$data[$key] = array_replace($data, $new);
}
}, UrbanWord::$data);
}
I tired running this but the original array will not update. I need help on how to go about fixing this please.
Thanks
You may use array_reduce instead of array_map as following:
public function update($array, $slang, $new)
{
return array_reduce($array, function ($result, $item) use ($slang, $new) {
if ($item['slang'] == $slang) {
$item = array_replace($item, $new);
}
$result[] = $item;
return $result;
}, array());
}
Usage:
UrbanWord::$data = $this->update(
UrbanWord::$data,
'Tight',
array('description' => 'another description')
);
var_dump($myUpdatedArray);
If you want to update it directly passing the UrbanWord::$data by reference you may try something like:
class UrbanWord
{
public static $data = array(
array(
'slang' => 'Test',
'Desc' => 'Frist Desc'
),
array(
'slang' => 'Test1',
'Desc' => 'Second Desc'
)
);
}
class MyClass
{
public function update(&$array, $slang, $new)
{
$array = array_reduce($array, function ($result, $item) use ($slang, $new) {
if ($item['slang'] == $slang) {
$item = array_replace($item, $new);
}
$result[] = $item;
return $result;
}, array());
}
}
$myClass = new MyClass();
$myClass->update(UrbanWord::$data, 'Test', array('Desc' => 'test'));
echo '<pre>';
var_dump(UrbanWord::$data);
echo '</pre>';
Related
I spent over 2 hours looking for the solution, and I leave it to you because I am completely blocked. I try to learn the object in PHP. I created a function that return me the result of an SQL query.
Here is the var_dump return :
object(stdClass)[6]
public 'name' =>
array (size=2)
0 =>
object(stdClass)[11]
public 'id' => string '1' (length=1)
1 =>
object(stdClass)[12]
public 'id' => string '5' (length=1)
I used a foreach to parse this, but I don't get directly the id of each element. And I especially don't want to use another foreach.
foreach($function as $key => $value){
var_dump($value->id);
}
But it doesn't work there.
Here is the function called who returns this result
public function nameFunction () {
$obj = new stdClass();
$return = array();
$request = $this->getConnexion()->prepare('SELECT id FROM table') or die(mysqli_error($this->getConnexion()));
$request->execute();
$request->store_result();
$request->bind_result($id);
while ($request->fetch()) {
$return[] = parent::parentFunction($id);
}
$obj->name = $return;
$request-> close();
return $obj;
}
And parent::parentFunction($id) returns :
object(stdClass)[11]
public 'id' => string '1' (length=1)
You are looping the object instead of array. Try to use this code
foreach($function->name as $key => $value){
var_dump($value->id);
}
Tell me if it works for you
This question might help you :
php parsing multidimensional stdclass object with arrays
Especially answer from stasgrin
function loop($input)
{
foreach ($input as $value)
{
if (is_array($value) || is_object($value))
loop($value);
else
{
//store data
echo $value;
}
}
}
I have a POST request array that looks like this
$request = array (size=2)
'licence' => string 'uDyQwFwqV7aQG2z' (length=15)
'user' =>
array (size=7)
'first_name' => string 'Danut' (length=5)
'last_name' => string 'Florian' (length=7)
'username' => string 'daniesy9' (length=8)
'password' => string '123456' (length=6)
'rpassword' => string '123456' (length=6)
'email' => string 'daniesy+1#me.com' (length=16)
'phone' => string '9903131' (length=7)
This in fact is an array which represents values sent by a form. I know the name of the elements, for example the username input has the name of user[username] and i have to find the related value from the array, by name. Something like:
$key = "user[username]";
$request[key];
Any idea how to do this?
I know that the correct way to do it is $request["user"]["username"] but it's quite complicated because i have to use the fields names from the form which are user[username], user[firstname], etc and it might have up to 4 levels of depth.
Answered in comments but similar Question to
Convert a String to Variable
eval('$username = $request["user"]["username"];');
Edit
Eval not a valid suggestion as request data.
So I would suggest the second method on this post
<?php
$request = array(
'user' => array(
'username' => 'joe_blogs'
)
);
function extract_data($string) {
global $request;
$found_matches = preg_match_all('/\[\"([a-z]+)\"\]/', $string, $matches);
if (!$found_matches) {
return null;
}
$current_data = $request;
foreach ($matches[1] as $name) {
if (key_exists($name, $current_data)) {
$current_data = $current_data[$name];
} else {
return null;
}
}
return $current_data;
}
$username = extract_data('request["user"]["username"]');
?>
function findInDepth($keys, $array){
$key = array_shift($keys);
if(!isset($array[$key])){
return FALSE;
}
if(is_array($array[$key])){
return findInDepth($keys, $array[$key]);
}
return $array[$key];
}
$key = "user[username]";
$keys = preg_split("/(\[|\])/", $key);
echo findInDepth($keys, $request);
This function solves my problem. It first splits the string (aka the input name) into an array of keys and then recessively searches in depth the array by keys until it finds a value which is not an array and returns FALSE otherwise.
You could separate keys with dots. Primitive example:
<?php
class ArrayDot
{
protected $array = [];
public function __construct(array $array) {$this->array = $array;}
public function get($path)
{
$array = $this->array;
foreach(explode('.', $path) as $key) {
$array = $array[$key];
}
return $array;
}
}
$array = [
'user' => [
'username' => 'tootski',
]
];
$a = new ArrayDot($array);
echo $a->get('user.username'); # tootski
I need to access the data: 'hotelID', 'name', 'address1','city' etc. I have the following Std Object array ($the_obj) in PHP that contains the following data:
object(stdClass)[1]
public 'HotelListResponse' =>
object(stdClass)[2]
public 'customerSessionId' => string '0ABAAA87-6BDD-6F91-4292-7F90AF49146E' (length=36)
public 'numberOfRoomsRequested' => int 0
public 'moreResultsAvailable' => boolean false
public 'HotelList' =>
object(stdClass)[3]
public '#size' => string '227' (length=3)
public '#activePropertyCount' => string '227' (length=3)
public 'HotelSummary' =>
array (size=227)
0 =>
object(stdClass)[4]
public 'hotelId' => 112304
public 'name' => La Quinta Inn and Suites Seattle Downtown
public 'address1' => 2224 8th Ave
public 'city' => Seattle
public 'stateProvinceCode' => WA
public 'postalCode' => 98121
public 'countryCode' => US
public 'airportCode' => SEA
public 'propertyCategory' => 1
public 'hotelRating' => 2.5
I have tried the following for lets say to access the 'name':
echo $the_obj->HotelListResponse->HotelList->HotelSummary[0]->name;
Also I have tried to print each key and value pairs by using foreach loop but I keep on getting errors. Here is what I tried:
foreach ($the_obj->HotelListResponse->HotelList->HotelSummary[0] as $key => $value){
echo $key.' : '.$value.'<br />';
}
Here are the errors that I get:
Trying to get property of non-object
Warning: Invalid argument supplied for foreach()
Thank you everyone for answering, I have figured out the way to access the 'hotelID', 'name' and all other keys and value pairs in the deepest nest of the array.
I converted the Std Object array to an associative array, then I accessed each of the value by using the foreach loop:
foreach ($the_obj["HotelListResponse"]["HotelList"]["HotelSummary"] as $value){
echo $value["hotelId"];
echo $value["name"];
//and all other values can be accessed
}
To access both (Keys as well as values):
foreach ($the_obj["HotelListResponse"]["HotelList"]["HotelSummary"] as $key=>$value){
echo $key.'=>'.$value["hotelId"];
echo $key.'=>'.$value["name"];
//and all other keys as well as values can be accessed
}
Regarding to #Satya's answer I'd like to show simpler way for Object to array conversion, by using json functions:
$obj = ...
$tmp = json_encode($obj);
$objToArray = json_decode($tmp,true);
This way you can easily access array items. First you can dump structure...
try something like this :
$p=objectToArray($result);
recurse($p);
}
function objectToArray( $object )
{
if( !is_object( $object ) && !is_array( $object ) )
{
return $object;
}
if( is_object( $object ) )
{
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
function recurse ($array)
{
//statements
foreach ($array as $key => $value)
{
# code...
if( is_array( $value ) )
{
recurse( $value );
}
else
{ $v=$value;
$v=str_replace("’",'\'',strip_tags($v));
$v=str_replace("–",'-',$v);
$v=str_replace("‘",'\'',strip_tags($v));
$v=str_replace("“",'"',strip_tags($v));
$v=str_replace("”",'"',strip_tags($v));
$v=str_replace("–",'-',strip_tags($v));
$v=str_replace("’",'\'',strip_tags($v));
$v=str_replace("'",'\'',strip_tags($v));
$v=str_replace(" ",'',strip_tags($v));
$v=html_entity_decode($v);
$v=str_replace("&",' and ',$v);
$v = preg_replace('/\s+/', ' ', $v);
if($key=="image")
{
if(strlen($v)==0)
{
echo '<'.$key .'>NA</'.$key.'>';
}
else
{
echo '<'.$key .'>'. trim($v) .'</'.$key.'>';
}
}
}
}
}
I have two arrays. One containing the data and other contains the keys. So I have
$data = array(
'name' => array('label' => 'Name:', 'value' => 'Genghis'),
'age' => array('label' => 'Age:', 'value' => '67'),
'weigh' => array('label' => 'Weigh in Kgs:', 'value' => '78')
);
and
$keys = array('name', 'age');
Now I want to extract only the name and age elements of $data. Some thing like this.
$extracted = somemethod($data, $keys);
var_export($extracted);
Output should be like this.
array(
'name' => array(
'label' => 'Name:',
'value' => 'Genghis',
),
'age' => array(
'label' => 'Age:',
'value' => '67',
),
)
How can i do this?
I would use an array_intersect_key() function like this:
$data = array(...); // initial array as described
$retained_keys = array('name' => 'value not used', 'age' => 'value not used');
$filtered_array = array_intersect_key($data, $retained_keys);
Loop over the keys, grab the array values, and return them:
function somemethod($data, $keys) {
$return = array();
foreach( $keys as $k) {
$return[$k] = isset( $data[$k]) ? $data[$k] : null;
}
return $return;
}
The above adds 'null' when a field isn't found. You can modify the foreach loop to just skip the key when it's not found in the $data array, like this:
function somemethod($data, $keys) {
$return = array();
foreach( $keys as $k) {
if( isset( $data[$k])) {
$return[$k] = $data[$k];
}
}
return $return;
}
Edit: To extend on Mike Brant's answer, array_intersect_key() can be used with array_flip() in a function to achieve the desired output:
function somemethod($data, $keys) {
$keys = array_flip( $keys);
return array_intersect_key($data, $keys);
}
Yes, it uses array_flip(), but the original $keys array is left unmodified, as a copy of that array is what gets flipped. So, you would still call this function with:
$extracted = somemethod( $data, array('name', 'age'));
Not exactly onerous to write
$extracted = array();
foreach($keys as $key) {
if (isset($data[$key]))
$extracted[$key] = $data[$key];
}
I have an array that looks like this:
array
0 =>
array
'title' => string 'Ireland - Wikipedia, the free encyclopedia'
'url' => string 'http://en.wikipedia.org/wiki/Ireland'
1 =>
array
'title' => string 'Ireland's home for accommodation, activities.'
'url' => string 'http://www.ireland.com/'
that I want to add a score of 0 to each element. I thought this simple foreach loop would do the trick but...well....it doesn't :/
public function setScore($result)
{
foreach($result as $key)
{
$key = array('title', 'url', 'score' => 0);
}
return $result;
}
Can someone help me out?
Thanks
foreach works on a copy of the array. You can modify $key all you want, it's not going to reflect on the original array.
You can use $key by reference though, then it'll work as expected:
foreach ($result as &$value) {
$value['score'] = 0;
}
Manual entry: http://php.net/manual/en/control-structures.foreach.php
You create a new array here and do nothing with it:
foreach($result as $key){
$key = array('title', 'url', 'score' => 0);
}
What you want to do is to modify a reference to existing one:
foreach($result as &$key){ # Note the '&' here
$key['score'] = 0;
}
Although deceze is right, you can also do this using array_walk(), like this:
array_walk( $result, function( &$el) { $el['score'] = 0; });
Here's an example of how to accomplish this.
$array = array( array( 'title' => "Ireland - Wikipedia, the free encyclopedia", 'url' => "http://en.wikipedia.org/wiki/Ireland"), array( 'title' => "Ireland's home for accommodation, activities.", 'url' => "http://www.ireland.com/" ) );
function setScore( $result )
{
foreach( $result as &$element )
{
$element['score'] = 0;
}
return $result;
}
$array = setScore( $array );
print_r( $array );
You could also do:
function setScore( &$result )
{...}
and then just:
setScore( $array );