I am trying to loop through each key but i am facing a problem of same value repeating inside for each loop
Here is example of my current code and result (click here)
here is my code so far
<?php
$data2 = array(
'category_name' => '33287*100*prescription*1,32457*1250*lab*1'
);
$result = array('0' => (object)$data2);
foreach ($result as $key => $category) {
$category_name = explode(',', $category->category_name);
}
$newresults=[];
foreach ($category_name as $key) {
$category->category_name = $key;
$newresults[]=$category;
}
$result=$newresults;
$newresults=[];
$category->items_count = 0;
foreach ($result as $key => $value) {
list($sale_key, $sale_value) = explode('*', $value->category_name);
// $category->items_count += count($sale_value);
$newresults[]=$category;
}
$result=$newresults;
i am expect the result should be
Array
(
[0] => stdClass Object
(
[category_name] => 33287*100*prescription*1
[items_count] => 0
)
[1] => stdClass Object
(
[category_name] => 32457*1250*lab*1
[items_count] => 0
)
)
The bug is that you're relying only on the last version of $category after you've finished looping it earlier - you'd have to be using it within the loop where it's assigned, in order to get each value in turn, or you could use $value from your last foreach loop.
But as a general observation, this code has way too many loops etc. just for processing one array in the way you've requested. Here's a much simpler version:
$category_name = '33287*100*prescription*1,32457*1250*lab*1';
$category_name_arr = explode(',', $category_name);
print_r($category_name_arr);
$newresults=[];
foreach ($category_name_arr as $cat) {
$newresults[] = (object) array("category_name" => $cat, "items_count" => 0);
}
print_r($newresults);
Demo: http://sandbox.onlinephpfunctions.com/code/065a32b40f67e00aa85f0f5b58ecacd510f2f38a
If you still need to be able to support multiple lines of input, you can do it like this, by just merging the exploded arrays before you process them:
$data = array(
'33287*100*prescription*1,32457*1250*lab*1',
'33222*900*prescription*3,22233*1200*lab*2',
);
$category_name_arr = [];
foreach ($data as $category_name)
{
$category_name_arr = array_merge($category_name_arr, explode(',', $category_name));
}
print_r($category_name_arr);
$newresults=[];
foreach ($category_name_arr as $cat) {
$newresults[] = (object) array("category_name" => $cat, "items_count" => 0);
}
print_r($newresults);
adding $category = new stdClass();
foreach ($category_name as $key) {
$category = new stdClass();
$category->category_name = $key;
$newresults[]=$category;
}
I am trying to get my XML format be like this:
but my code now does not loop for the 'order_line' array and will return like this:
below are sample of my code I did:
$result = $this->db->query("SELECT * FROM `grn_order` a");
foreach($result->result() as $row )
{
$result_line = $this->db->query("SELECT * FROM `grn_order_line` a where a.order_no = '$row->order_no'");
foreach($result_line->result() as $row_line);
{
$line = array(
'guid' => $row_line->guid,
'itemcode' => $row_line->itemcode,
);
}
$my_array[] = array(
'order_no' => $row->order_no,
'loc_code' => $row->loc_code,
'trans_code' => $row->trans_code,
'po_no' => $row->po_no,
'order_line' => $line
);
} $xml = new SimpleXMLElement('<orders/>');
// function callback
$data = $this->array2XML($xml, $my_array);
print $xml->asXML();
function array2XML($obj, $array)
{
foreach ($array as $key => $value)
{
if(is_numeric($key))
$key = 'order';
if (is_array($value))
{
$node = $obj->addChild($key);
$this->array2XML($node, $value);
}
else
{
$obj->addChild($key, htmlspecialchars($value));
}
}
}
You keep on overwriting the last line in your load loop. Change it to...
$line = [];
foreach($result_line->result() as $row_line);
{
$line[] = array(
'guid' => $row_line->guid,
'itemcode' => $row_line->itemcode,
);
}
So each line is added using $line[].
I am fetching data from location MySql table as structure is below
in my PHP code
I need send Json output in response as below (Table data may not be same as below json data but the format is same)
http://jsoneditoronline.org/?id=7c5600712df6f9ec1f8fbb8a13aba3de
Tried to do the following in the code to convert the array that i fetch from the table but however am unable to get it in the right format
$sql = "SELECT * FROM mobile_user_regions";
$stmt = $this->db->prepare($sql);
$stmt->execute();
$resCArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
$ress = array();
foreach ($resCArray as $key => $value) {
$ress['regions'][] = array(array(
'name' => $value['region'],
'location' => array(
array(
'name' => $value['location'],
'store' => array(
'store_details' => $value['store_details'],
'store_phone' => $value['store_phone'],
'store_email' => $value['store_email'],
'store_latitude' => $value['store_latitude'],
'store_longitude' => $value['store_longitude']
)
)
)
)
);
Output: that i am getting is
**http://jsoneditoronline.org/?id=4d4a75177350e254ceee7238af13f2f7**
$regionArray = $xyzObject->getRegion();
if (!empty($regionArray) && isset($regionArray)) {
$i = 0;
$locationData = array();
foreach ($regionArray as $key => $value) {
$locationData['regions'][$i]['name'] = $value['region'];
$locationArray = $xyzObject->getLocation($value['region']);
$locationData['regions'][$i]['locations'] = $locationArray;
$i++;
}
$j = 0;
foreach ($locationData['regions'] as $key => $regions) {
$k = 0;
foreach ($regions['locations'] as $key1 => $locations) {
$storeArray = $xyzObject->getStore($locations['name']);
$locationData['regions'][$j]['locations'][$k]['stores'] = $storeArray;
$k++;
}
$j++;
}
echo json_encode($locationData);
I came up with this ugly verbose array (and I have to use it):
$puppy_mother_father_arr = array(
array('46' => array('30','29')),
array('17' => array('30','29')),
array('16' => array('24','29'))
);
How do I simplify it to something like this :
$puppy_mother_father_arr = array(
'46' => array('30','29'),
'17' => array('30','29'),
'16' => array('24','29')
);
I've been stuck a day in here. thanks in advance
$tmp = array();
foreach ($puppy_mother_father_arr as $parent) {
foreach($parent as $key => $nodes) {
$tmp[$key] = $nodes;
}
}
$puppy_mother_father_arr = $tmp;
Would this work?
See the result online
<?php
$puppy_mother_father_arr = array( array('46' => array('30','29')),array('17' => array('30','29')),array('16' => array(24,'29')) );
$list = array();
foreach ($puppy_mother_father_arr as $info)
{
foreach ($info as $key => $value)
{
$list[$key] = $value;
break;
}
}
var_export($list);
$newarray = array();
foreach ($puppy_mother_father_arr as $array) {
foreach ($array as $puppy => $parents) {
$newarray[$puppy] = $parents;
}
}
$puppy_mother_father_arr = $newarray;
key and current could be useful if each array has only one interested key and value:
$result = array();
foreach($puppy_mother_father_arr as $arr) {
$result[key($arr)] = current($arr);
}
var_dump($result);
In an array such as the one below, how could I rename "fee_id" to "id"?
Array
(
[0] => Array
(
[fee_id] => 15
[fee_amount] => 308.5
[year] => 2009
)
[1] => Array
(
[fee_id] => 14
[fee_amount] => 308.5
[year] => 2009
)
)
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['fee_id'];
unset($array[$k]['fee_id']);
}
This should work
You could use array_map() to do it.
$myarray = array_map(function($tag) {
return array(
'id' => $tag['fee_id'],
'fee_amount' => $tag['fee_amount'],
'year' => $tag['year']
); }, $myarray);
$arrayNum = count($theArray);
for( $i = 0 ; $i < $arrayNum ; $i++ )
{
$fee_id_value = $theArray[$i]['fee_id'];
unset($theArray[$i]['fee_id']);
$theArray[$i]['id'] = $fee_id_value;
}
This should work.
Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?
foreach ($array as $arr)
{
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
There is no function builtin doing such thin afaik.
This is the working solution, i tested it.
foreach ($myArray as &$arr) {
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
The snippet below will rename an associative array key while preserving order (sometimes... we must). You can substitute the new key's $value if you need to wholly replace an item.
$old_key = "key_to_replace";
$new_key = "my_new_key";
$intermediate_array = array();
while (list($key, $value) = each($original_array)) {
if ($key == $old_key) {
$intermediate_array[$new_key] = $value;
}
else {
$intermediate_array[$key] = $value;
}
}
$original_array = $intermediate_array;
Converted 0->feild0, 1->field1,2->field2....
This is just one example in which i get comma separated value in string and convert it into multidimensional array and then using foreach loop i changed key value of array
<?php
$str = "abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu;
echo '<pre>';
$arr1 = explode("\n", $str); // this will create multidimensional array from upper string
//print_r($arr1);
foreach ($arr1 as $key => $value) {
$arr2[] = explode(",", $value);
foreach ($arr2 as $key1 => $value1) {
$i =0;
foreach ($value1 as $key2 => $value2) {
$key3 = 'field'.$i;
$i++;
$value1[$key3] = $value2;
unset($value1[$key2]);
}
}
$arr3[] = $value1;
}
print_r($arr3);
?>
I wrote a function to do it using objects or arrays (single or multidimensional) see at https://github.com/joaorito/php_RenameKeys.
Bellow is a simple example, you can use a json feature combine with replace to do it.
// Your original array (single or multi)
$original = array(
'DataHora' => date('YmdHis'),
'Produto' => 'Produto 1',
'Preco' => 10.00,
'Quant' => 2);
// Your map of key to change
$map = array(
'DataHora' => 'Date',
'Produto' => 'Product',
'Preco' => 'Price',
'Quant' => 'Amount');
$temp_array = json_encode($original);
foreach ($map AS $k=>$v) {
$temp_array = str_ireplace('"'.$k.'":','"'.$v.'":', $temp);
}
$new_array = json_decode($temp, $array);
Multidimentional array key can be changed dynamically by following function:
function change_key(array $arr, $keySetOrCallBack = [])
{
$newArr = [];
foreach ($arr as $k => $v) {
if (is_callable($keySetOrCallBack)) {
$key = call_user_func_array($keySetOrCallBack, [$k, $v]);
} else {
$key = $keySetOrCallBack[$k] ?? $k;
}
$newArr[$key] = is_array($v) ? array_change_key($v, $keySetOrCallBack) : $v;
}
return $newArr;
}
Sample Example:
$sampleArray = [
'hello' => 'world',
'nested' => ['hello' => 'John']
];
//Change by difined key set
$outputArray = change_key($sampleArray, ['hello' => 'hi']);
//Output Array: ['hi' => 'world', 'nested' => ['hi' => 'John']];
//Change by callback
$outputArray = change_key($sampleArray, function($key, $value) {
return ucwords(key);
});
//Output Array: ['Hello' => 'world', 'Nested' => ['Hello' => 'John']];
I have been trying to solve this issue for a couple hours using recursive functions, but finally I realized that we don't need recursion at all. Below is my approach.
$search = array('key1','key2','key3');
$replace = array('newkey1','newkey2','newkey3');
$resArray = str_replace($search,$replace,json_encode($array));
$res = json_decode($resArray);
On this way we can avoid loop and recursion.
Hope It helps.