PHP extract values from array - php

I'm trying to extract values from an array within an array. The code I have so far looks like this:
$values = $request->request->get('form');
$statusArray = array();
foreach ($values->status as $state) {
array_push($statusArray, $state);
}
The result of doing a var_dump on the $values field is this:
array (size=2)
'status' =>
array (size=2)
0 => string 'New' (length=9)
1 => string 'Old' (length=9)
'apply' => string '' (length=0)
When running the above I get an error basically saying 'status' isn't an object. Can anyone tell me how I can extract the values of the array within 'status'??

-> it's the notation to access object values, for arrays you have to use ['key']:
foreach ($values['status'] as $state) {
array_push($statusArray, $state);
}
Object example:
class Foo {
$bar = 'Bar';
}
$foo = new Foo();
echo $foo->bar // prints "bar"

Related

Get the element with array and object

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

Create nested arrays from specific variables within session

I have several values stored in $_SESSION beginning with 'first_name_' & 'last_name_' which then a number appended to the end deepening on how many names are generated.
I am able to extract each of these values from the session and add to an array but would like to pair up the first and last names together within a nested array. (if that makes sense)
at the moment I have:
$users_array = array();
foreach ($_SESSION as $key => $value) {
if(strpos($key, 'first_name_') === 0) {
$users_array[] = $value;
}
if(strpos($key, 'last_name_') === 0) {
$users_array[] = $value;
}
}
This produces an output with var_dump:
array
0 => string 'John' (length=4)
1 => string 'Smith' (length=8)
2 => string 'Jane' (length=4)
3 => string 'Doe' (length=3)
But what I would like is something like:
array
'user' =>
array
'first_name' => string 'John' (length=4)
'last_name' => string 'Smith' (length=5)
array
'first_name' => string 'Jane' (length=4)
'last_name' => string 'Doe' (length=5)
Any suggestions on how I can achieve this?
deceze is right in his comment... But just so people with similar issues with creating 2-dimensional array from a 1-dimensional array, here is a solution. Also, note that PHP does not guarantee that the order will be same when iterating using FOREACH. As this will work, it is still prone to errors.
$users_array = array();
foreach ($_SESSION as $key => $value) {
if(strpos($key, 'first_name_') === 0) {
$users_array[] = array();
$users_array[count($users_array)-1]['first_name'] = $value;
}
if(strpos($key, 'last_name_') === 0) {
$users_array[count($users_array)-1]['last_name'] = $value;
}
}

How to extract array data in PHP variable with foreach?

I need to extract last array data i.e SiteName, Url, Title to the variable in php.
array
'ApplicableProductOfferings' =>
array
0 => string 'EasyDemo' (length=10)
'Artist' => string 'Hello' (length=10)
'ReferralDestinations' =>
array
0 =>
array
'SiteName' => string 'gettyimages' (length=11)
'Url' => string 'http://www.gettyimages.com/detail/160414706' (length=43)
'Title' => string 'Pixie Lott Launches The New BlackBerry Z10' (length=42)
'UrlComp' => string 'http://localhost.com' (length=197)
'UrlPreview' => string 'http://localhost.com' (length=164)
'UrlThumb' => string 'http://localhost.com' (length=82)
'UrlWatermarkComp' => string 'http://localhost.com' (length=197)
'UrlWatermarkPreview' => string 'http://localhost.com
try this.......
foreach($data as $dat)
{
foreach($dat['ReferralDestinations'] as $key => $d)
{
echo $d['SiteName'];
echo $d['Url'];
echo $d['Title'];
}
}
It depends on how you are storing the data in the array. If you have an array that already has the last array data, it's very simple.
foreach ($myArray as $var) {
echo $var;
}
or access individual elements as $myArray['SiteName'], $myArray['Url'] etc..
Assuming you have the above data in an array of arrays called $arrayOfArrays
foreach ($arrayOfArrays as $myArray) {
// $myArray now holds first array, second array etc as the loop is executed
// First time it holds 'ApplicableProductOfferings', second time 'ReferralDesinations'..
// If the array is 'ReferralDesitnations' you can loop through that array
// to get the elements you are looking for SiteName etc as below
foreach ($myArray as $URLElement) {
echo $URLElement;
}
}
$array1 = [];
$array2 = [];
foreach ($array1 as $key=> $val) {
extract($array2, EXTR_IF_EXISTS, $val);
}
// extract() flags => EXTR_IF_EXISTS ...
// http://php.net/manual/ru/function.extract.php

Different way to convert object to array using PHP

When use this code:
$array=(array)$yourObject;
The properties of $yourObject convert to index an array, but how can convert as one array, these means, the $yourObject be one index of $array and I echo $array[0] for access through object?!
Another way for question, please see this sample code:
<?php
$var1 = (string) 'a text';
$var2 = (array) array('foo', 'bar');
$var3 = (object) array("foo" => 1, "bar" => 2);
//It's OK.
foreach((array)$var1 as $v) {
echo $v."<br>";
}
echo "<hr>";
//It's OK.
foreach((array)$var2 as $v) {
echo $v."<br>";
}
echo "<hr>";
//It's NOT OK. I want through $var3 in output as an array with one index!
foreach((array)$var3 as $v) {
echo $v."<br>";
}
echo "<hr>";
?>
Other way:
I want use a variable in foreach but I not sure about type this, I want working foreach without error for any type variable (string, array, object,...)
For example I thinks must I have this sample output for some this types:
Output for $var1:
array
0 => string 'a text' (length=6)
Output for $var2:
array
0 => string 'foo' (length=3)
1 => string 'bar' (length=3)
Output for $var3:
array
0 =>
object(stdClass)[1]
public 'foo' => int 1
public 'bar' => int 2
And the end I sure the foreach return current result without error.
You mean to wrap your object inside an array?
$array = array($yourObject);
As mentioned by mc10, you can use the new short array syntax as of PHP 5.4:
$array = [$yourObject];

Getting JSON data in PHP

I have a JSON data like this:
{
"hello":
{
"first":"firstvalue",
"second":"secondvalue"
},
"hello2":
{
"first2":"firstvalue2",
"second2":"secondvalue2"
}
}
I know how to retrieve data from object "first" (firstvalue) and second (secondvalue) but I would like to loop trough this object and as a result get values: "hello" and "hello2"...
This is my PHP code:
<?php
$jsonData='{"hello":{"first":"firstvalue","second":"secondvalue"},"hello2":{"first2":"firstvalue2","second2":"secondvalue2"}}';
$jsonData=stripslashes($jsonData);
$obj = json_decode($jsonData);
echo $obj->{"hello"}->{"first"}; //result: "firstvalue"
?>
Can it be done?
The JSON, after being decoded, should get you this kind of object :
object(stdClass)[1]
public 'hello' =>
object(stdClass)[2]
public 'first' => string 'firstvalue' (length=10)
public 'second' => string 'secondvalue' (length=11)
public 'hello2' =>
object(stdClass)[3]
public 'first2' => string 'firstvalue2' (length=11)
public 'second2' => string 'secondvalue2' (length=12)
(You can use var_dump($obj); to get that)
i.e. you're getting an object, with hello and hello2 as properties names.
Which means this code :
$jsonData=<<<JSON
{
"hello":
{
"first":"firstvalue",
"second":"secondvalue"
},
"hello2":
{
"first2":"firstvalue2",
"second2":"secondvalue2"
}
}
JSON;
$obj = json_decode($jsonData);
foreach ($obj as $name => $value) {
echo $name . '<br />';
}
Will get you :
hello
hello2
This will work because foreach can be used to iterate over the properties of an object -- see Object Iteration, about that.

Categories