I have an existing JSON array:
stdClass Object
(
[set] => Array
(
[0] => stdClass Object
(
[name] => agenda
)
[1] => stdClass Object
(
[name] => first aid
)
)
)
I need to add a new key to it, so the final JSON result is something like this:
set: [{
name: 'agenda',
value: 'Agenda'
}, {
code: 'first aid',
value: 'First Aid'
}],
This is what I've done so far:
$result = array();
foreach ($data->set as $k => $row) {
$result['name'][$k] = $row->name;
$result['value'][$k] = ucwords($row->name);
}
But I have ended up with:
Array
(
[name] => Array
(
[0] => agenda
[1] => aid kit
)
[value] => Array
(
[0] => Agenda
[0] => First Aid
)
)
How can I merge the above so the name and value keys are in pair rather then being separate?
Update $row directly to modify your existing $data:
foreach ($data->set as $row) {
$row->value = ucwords($row->name);
}
To do it the way you are attempting:
$result = $data;
foreach ($data->set as $k => $row) {
$result->set[$k]->value = ucwords($row->name);
}
Notice, $row is an object.
Your try this
$result = array();
$count = 0;
foreach ($data->set as $k => $row) {
$result[$count]['name'] = $row->name;
$result[$count]['value'] = ucwords($row->name);
$count++;
}
result this
Array
(
[0] => stdClass Object
(
[name] => agenda
[value] => Agenda
)
[1] => stdClass Object
(
[name] => first aid
[value] => First Aid
)
)
If you want to modify your existing object, you can just set the value property directly.
foreach ($data->set as $row) {
$row->value = ucwords($row->name);
}
If you want to create a result without modifying your original object or leaving references to its internal objects, you can clone each of the internal objects and add the new properties to the cloned objects.
$result = array();
foreach ($data->set as $k => $row) {
$obj = clone $row;
$obj->value = ucwords($row->name);
$result[$k] = $obj;
}
Related
In a foreach loop i would like to compare [name] value beetween different arrays but they have not the same levels.
Array(
[array1] => Array
(
[0] => WP_Term Object
(
[name] => Plafond
)
)
[array2] => WP_Term Object
(
[name] => Chaudière
)
[array3] => Array
(
[0] => WP_Term Object
(
[name] => Pla
)
[1] => WP_Term Object
(
[name] => Toc
)
)
)
I don't know how could i get the [name] in the same loop whereas levels are different.
I have tried to make :
foreach( $fields as $name => $value )
{
echo $value->name; }
Should i add another loop in the first loop ?
thanks
So your data looks like this:
$json = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$array = json_decode($json);
If you don't know how deep it will go, a simple recursive function should work. Perhaps something like this:
function get_name($o, &$output) {
if (is_array($o)) {
foreach($o as $v) {
get_name($v, $output);
}
} elseif (property_exists($o, "name")) {
$output[] = $o->name;
}
}
$output = [];
foreach ($array as $v) {
get_name($v, $output);
}
If you data is going to look like the sample you provided (i.e. it will always be first or second level) then you don't need to worry about recursion.
$output = [];
foreach ($array as $k=>$v) {
if (is_array($v)) {
foreach ($v as $k2=>$v2) {
$output[] = $v2->name;
}
} else {
$output[] = $v->name;
}
}
Either way, your output values are all in the $output array:
print_r($output);
Output:
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use array_map, array_key_exists to retrive the name index from the array
$jsonFormat = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$jsonArray = json_decode($jsonFormat,true);
$res = [];
array_map(function($v) use (&$res){
if(array_key_exists('name', $v)){
$res[] = $v['name'];
}else{
foreach($v as $_key => $_value){
$res[] = $_value['name'];
}
}
}, $jsonArray);
echo '<pre>';
print_r($res);
Result:-
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use $res to compare the names.
What I'm trying to do:
Get results from the database.
Get required values by assigning to an stdClass.
Put those objects in array. (<-The problem)
And output as JSON.
The objects are fine they get correct values. But when they are assigned to the array once, they replace all previous array values.
I'm using CodeIgniter to do the DB stuff.
The function:
function get_prizes(){
//All prize objects are stored here
$prizes = array();
//Prize object
$prize = new stdClass();
$prize->name1 = '';
//$prize->type = '';
//Getting the prizes from a simple database table
$query = $this->db->get('prizes');
if($query->num_rows() > 0){
foreach ($query->result() as $row):
$prize_name = $row->prize_name;
$prize->name1 = $prize_name;
//$prize->type = $prize_name;
$prizes[] = $prize;
echo " Item: " . print_r($prizes, true) . "<br>";
endforeach;
}
echo json_encode($prizes);
}
Output:
Item: Array ( [0] => stdClass Object ( [name1] => Radio ) )
Item: Array ( [0] => stdClass Object ( [name1] => Television ) [1] => stdClass Object ( [name1] => Television ) )
Item: Array ( [0] => stdClass Object ( [name1] => Toaster ) [1] => stdClass Object ( [name1] => Toaster ) [2] => stdClass Object ( [name1] => Toaster ) )
[{"name1":"Toaster"},{"name1":"Toaster"},{"name1":"Toaster"}]
I've tried array_push(). Also does the same thing.
You need to instantiate the object inside foreach loop:
function get_prizes()
{
// All prize objects are stored here
$prizes = array();
// Getting the prizes from a simple database table
$query = $this->db->get('prizes');
if ($query->num_rows() > 0) {
foreach($query->result() as $row):
// Prize object
$prize = new stdClass();
// $prize->type = '';
$prize->name1 = $row->prize_name;
$prizes[] = $prize;
endforeach;
}
echo json_encode($prizes);
}
I try to create an generic object which needs to be structuered like this:
[Content] => stdClass Object
(
[item] => Array
(
[0] => stdClass Object
(
[Value] => STRING
)
)
[item] => Array
(
[0] => stdClass Object
(
[Value] => ANOTHER STRING
)
)
)
This is my code:
$content = new stdClass();
$data = file('filname.csv');
foreach($data as $key => $val) {
$content->item->Value = $val;
}
This overwrites itself each time the loop iterates. By defining item as an array like this:
$content->item = array();
...
$content->item[]->Value = $val;
...the result is also not the estimated.
You are overwritting data each time even using array. You should create temporary object for storing value and then put them to item array.
$content = new \stdClass();
$content->item = array();
foreach($data as $key => $val) {
$itemVal = new \stdClass();
$itemVal->Value = $val;
$content->item[] = $itemVal;
}
I have this array
Array (
[0] => stdClass Object (
[id] => 252062474)
[1] => stdClass Object (
[id] => 252062474)
[3] => stdClass Object (
[id] => 252062474)
)
I need echo all of id's
I tried,
foreach($result as $item) {
echo $item->id;
}
but no luck
I try json_decode()
again no luck I use php 5.5.8
I know this work
echo $item[0]->id;
but i don't how many index is there
any idea?
Maybe you are confused on foreach(). If this works:
echo $item[0]->id;
Then you would need:
foreach($item as $result) {
echo $result->id;
}
Try this-
Code
foreach($result as $p) {
echo $p['id'] . "<br/>";
}
Output
252062474
252062474
252062474
This array could be looped through and data could be retrieved. As you are saying its not working I have added the following code to illustrate how it works right from generating the array for you.
// generating an array like you gave in the example. Note that ur array has same value
// for all the ids in but my example its having different values
$arr = array();
$init = new stdClass;
$init->id = 252062474 ;
$arr[] = $init;
$init = new stdClass;
$init->id = 252062475 ;
$arr[] = $init;
$init = new stdClass;
$init->id = 252062476 ;
$arr[] = $init;
print_r($arr);
The above array is same as yours
Array ( [0] => stdClass Object ( [id] => 252062474 )
[1] => stdClass Object ( [id] => 252062475 )
[2] => stdClass Object ( [id] => 252062476 )
)
Now the following code will loop through and get the data as
foreach($arr as $key=>$val){
echo $key.' ID is :: '.$val->id;
echo '<br />';
}
The output will be
0 ID is :: 252062474
1 ID is :: 252062475
2 ID is :: 252062476
Try this
foreach($result as $item) {
$item = (array)$item;
echo $item['id'];
}
<root>
<gallery name="First"/>
<gallery name="Second"/>
<gallery name="Third"/>
</root>
I'm trying to rename multiple "name" attributes at once:
$rename = array();
foreach($_POST['name'] as $value) {
$rename[] = $value;
}
$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$gallery = $objXML->xpath('/root/gallery/#name');
print_r($gallery);
print_r($rename);
$objXML->asXML(XML_FILE_NAME);
Returns:
Array ( [0] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => First ) ) [1] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => Second ) ) [2] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => Third ) ) )
Array ( [0] => First New [1] => Second New [2] => Third New )
How can I get php to save the New values back to the XML? Does it need another foreach loop? The code seems to be getting too complex already.
I'm trying this, but no dice:
foreach( $objXML->xpath('/root/gallery/#name') as $gallery ) {
$gallery = $_POST['name'];
}
Simplexml is buid to returns node only. That's weird, but '/root/gallery/#name' and '/root/gallery'.
These two queries
$aList = $objXML->xpath('/root/gallery/#name');
$bList = $objXML->xpath('/root/gallery');
will return the same instances
for($i=0, $count=count($aList); $i<$count; $i++) {
$a = $aList[$i];
$b = $aList[$i];
var_dump($a==$b); // true
}
So the only way for changing the attribute of a node is with the array syntaxe
foreach($aList as $node) {
$node['name'] = 'foo' . $i;
}
var_dump($objXML);