Do foreach on a object in php - php

How do i perform foreach on a object . I wish to format the result that i get in my ci query
foreach ($CIResult as $key => $value) {
$CIResult -> $key = MyCustomFunction($value);
}
EDIT
I want CIResult to stay as a object only

foreach ($CIResult as $key => &$value) {
$value = MyCustomFunction($value);
}
It's important to note that this will only work on public properties of your object.

You can always cast an object to an array.

foreach ($CIResult as &$object) //by reference
{
$object->property = $new_value;
}

Is this what you want ?
foreach ($CIResult as $ciObj) {
// Access object properties like
$ciObj->property_name = format_name($ciObj->property_name);
}
Can you please, be more explicit on what you want to format ?

foreach((array)$CIResult as $key => $value)
$CIResult->$key = MyCustomFunction($value);

Related

Passing an object keys value to array

Language : PHP,
Framework : Laravel,
I have a collection of array.
I want to create a new array for each key and push all the variables to the array.
I have done the following code which looks ugly.
Is there some better way to do this.
I have created an new array for key using foreach loop and then passed the value to the array again using foreach loop.
$resultLabels = [];
foreach ($results as $result) {
foreach($result as $key => $value){
array_push($resultLabels,'ward_no ' .$value);
}
}
foreach ($results as $result){
foreach($result as $key => $value){
if($key != 'ward_no'){
array_push($arrays[$key],$value);
}
}
}
You don't need another nested loop. Have a look here:
$resultLabels = [];
foreach ($results as $result){
foreach($result as $key => $value){
array_push($resultLabels,'ward_no ' .$value);
if($key != 'ward_no'){
array_push($arrays[$key],$value);
}
}
}

how to split stored variables name inside foreach

How can i know the variables ?
foreach($tree as $key => $value){
if (in_array($value['name'], $arr_folders)) {
${'id_'.$value['name']} = $value['id'];
}
//how to know variables?
$id_???
Currently I know the $value['name'] ie. it may be one,two, three, etc. but how to use them
echo $id_one;
I wanted to know here to split them in an array. So i can use
print_r($vars); which would result $id_one, $id_two, etc..
Something like this?
<?php
$array = [];
foreach($tree as $key => $value){
if (in_array($value['name'], $arr_folders)) {
$array[] = $value['id'];
}
}
print_r($array);
You can find variables by code:
foreach (get_defined_vars() as $var_name => $var_value) {
if(strpos($var_name, 'id_') ===0 ){
//it's your variable
}
}
But store variable in local scope look wrong.
May be better store to an other array:
$arIds = array();
foreach($tree as $key => $value){
if (in_array($value['name'], $arr_folders)) {
$arIds['id_'.$value['name']] = $value['id'];
}
}

Accessing Certain JSON Elements

How would I go about accessing these elements from a Shopify JSON in PHP
JSON:
{
"orders":[
{ "note_attributes":[
{
"name":"field1",
"value":"xxxxxxxxxxxx"
},
{
"name":"field2",
"value":"xxxxxx"
},
{
"name":"field3",
"value":"xxxxxx"
}
],
This is just snippet of the object. How would I access each value and assign it to the name? Eg this $req['account_id'] would equal the value for that name tag. This is how am trying to do it but it's not working:
foreach ($order['note_attributes'] as $attributes) {
$req = array();
$req[$attributes->name] = $attributes[$attributes->value];
}
I would then like to echo $req['account_id'] and that would = xxxxxxxxx#gmail.com but it's not working any suggestions or fixes?
When iterating over Objects properties, one approach is to use (as you have) foreach
// accessing property
foreach ($objects as $object) {
echo $object->property;
}
// accessing key-value pair
foreach ($object as $key => $value) {
echo "$key => $value\n";
}
An example:
$attributes = array();
.
.
foreach($note_attributes as $note_attribute) {
$key = $note_attribute['name'];
$value = $note_attribute['value'];
$attributes[$key] = $value;
}
The structure should be in key-value pairs. ie.
attributes [
"account1234" => "abc#xxx.com",
"account_password" => "asdasdasd"
]
Hope this helps.
Update: as Roopendra mentioned, json_decode() with a TRUE flag with return an associative array, else stdClass.

How to parse Json data in php?

[{"name":"se","value":"test1"},{"name":"model","value":"test2"},{"name":"filter_preference","value":"test3"},{"name":"seved","value":"test4"}]
I have json, and I would like to parse it, and to get for "segment" => "test1"
and so on.
i have done this
$json2= json_encode($loadFilter);
$json2 = json_decode($json2, true);
foreach ($json2->$key as $value)
{
echo $key ."=>".$value;
}
always getting Invalid argument supplied for foreach() !!!
I am doing it WP ajax callback.
Your foreach syntax is wrong to access the $key.
foreach ($json2 as $key => $value) {
echo $key ."=>".$value;
}
Edit from your comments:
You didn't give the "real" format in your question, your array is contained in 'filter_preference', so you have to iterate over $json2['filter_preference'].
foreach ($json2['filter_preference'] as $key => $value) {
echo $key ."=>".$value;
}
you need to map key value for sub array.
try this:
foreach ($json2 as $key=>$value)
{
echo $key ."=>".$value;
}
One odd suggestion here:
If you want to use array for this then you can convert object to array using following code:
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
$array_new = objectToArray($json2);
http://wonderphp.wordpress.com/2014/03/20/convert-object-to-array-and-vice-versa/

Changing value inside foreach loop doesn't change value in the array being iterated over

Why does this yield this:
foreach( $store as $key => $value){
$value = $value.".txt.gz";
}
unset($value);
print_r ($store);
Array
(
[1] => 101Phones - Product Catalog TXT
[2] => 1-800-FLORALS - Product Catalog 1
)
I am trying to get 101Phones - Product Catalog TXT.txt.gz
Thoughts on whats going on?
EDIT: Alright I found the solution...my variables in my array had values I couldn't see...doing
$output = preg_replace('/[^(\x20-\x7F)]*/','', $output);
echo($output);
Cleaned it up and made it work properly
The doc http://php.net/manual/en/control-structures.foreach.php clearly states why you have a problem:
"In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference."
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>
Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code won't work:
<?php
/** this won't work **/
foreach (array(1, 2, 3, 4) as &$value) {
$value = $value * 2;
}
?>
Try
foreach( $store as $key => $value){
$store[$key] = $value.".txt.gz";
}
The $value variable in the array is temporary, it does not refer to the entry in the array.
If you want to change the original array entry, use a reference:
foreach ($store as $key => &$value) {
// ^ reference
$value .= '.txt.gz';
}
You are rewriting the value within the loop, and not the key reference in your array.
Try
$store[$key] = $value.".txt.gz";
pass $value as a reference:
foreach( $store as $key => &$value){
$value = $value.".txt.gz";
}
Try
$catalog = array();
foreach( $store as $key => $value){
$catalog[] = $value.".txt.gz";
}
print_r ($catalog);
OR
foreach( $store as $key => $value){
$store[$key] = $value.".txt.gz";
}
print_r ($store);
Depends on what you want to achieve
Thanks
:)
I believe this is what you want to do:
foreach( $store as $key => $value){
$store[$key] = $value.".txt.gz";
}
unset($value);
print_r ($store);
How about array map:
$func = function($value) { return $value . ".txt.gz"; };
print_r(array_map($func, $store));
foreach(array_container as & array_value)
Is the way to modify array element value inside foreach loop.

Categories