I would like to add all array elements to another array as elements
Here is my codes
<pre>
$resultBasedBuild = array();
$data = {0.225, 0.132, 0.114};
$index = 0;
foreach ($data as $singleData) {
$resultBasedData[] = array(
'name' => 'my name'
,'data' => array(array($index, $singleData))
);
}
$result = json_encode($resultBasedData);
</pre>
The expected output would be
[{"name":"20140722.1304","data":[[0,0.225],[0,0.132],[0,0.114]]}]
Thank you for your help.
I sorted this problem using one more array.
$data = [0.225, 0.132, 0.114];
$result = json_encode(['name' => 'my name', 'data' => array_map(function ($item)
{
return [0, $item];
}, $data)]);
Related
Trying to create a JSON array for Morris.js donut chart, but cant think of any way to get correct format. Any tips?
My controller:
$user = User::find((Auth::user()->id));
$budget = $user->budget()->get();
$labels = ['rent', 'heating', 'utilities', 'internet_tv', 'phone', 'food', 'sweets', 'alcohol_cigs', 'insurance' , 'loans', 'finance_other', 'cosmetics'
, 'medicine', 'clothes_shoes', 'accessories', 'electronics', 'school', 'entertainment', 'food_out', 'holidays', 'books', 'pets', 'gifts', 'car', 'other'];
$data2 = [];
foreach ($labels as $label)
{
$data2['label'][] = $label;
$data2['value'][] = $budget->sum($label);
}
$data2 = json_encode($data2);
What I am getting:
'{"label":["rent","heating","utilities","internet_tv" ...],"value":[435,30,0,0 ...]}'
I want to get:
'[{"label":"rent","value":"435"},{"label":"heating","value":"30"},{"label":"utilities","value":"0"},{"label":"internet_tv","value":"0"} ...]'
Your code is creating two subarrays to the $data2 array, one label and one value. Then, data is pushed to these two arrays over and over again.
Instead, you want to create a new array and push that one onto the $data2 array, like this:
$data2 = [];
foreach ($labels as $label)
{
$data2[] = [
'label' => $label,
'value' => $budget->sum($label)
];
}
first array like this
$zones_array1 = array();
$zones_array1[] = array('id' => 'Alabama', 'text' => 'Alabama');
$zones_array1[] = array('id' => 'Alaska', 'text' => 'Alaska');
$zones_array1[] = array('id' => 'Arizona', 'text' => 'Arizona');
$zones_array1[] = array('id' => 'Arkansas', 'text' => 'Arkansas');
second array like this
$zones_array2 = array();
$zones_array2[] = array('id' => 'Alaska', 'text' => 'Alaska');
$zones_array2[] = array('id' => 'Arizona', 'text' => 'Arizona');
i want filter these two array and i want final result as array like this
first array like this
$zones_array3 = array();
$zones_array3[] = array('id' => 'Alabama', 'text' => 'Alabama');
$zones_array3[] = array('id' => 'Arkansas', 'text' => 'Arkansas');
please help me
You can use php 'in_array' to check weather an element exists inside other array or not. In you case the array is multidimensional so stored all the id's inside a newly created array and then compared the given array with that.
$check_array = array();
foreach ($zones_array1 as $arr1){
$check_array[] = $arr1['id'];
}
$zones_array3 = array();
foreach ($zones_array2 as $arr2){
if (!in_array($arr2['id'], $check_array))
{
$zones_array3[] = $arr2;
}
}
echo '<pre>';
print_r($zones_array3);
Simply try:
function udiffCompare($a, $b)
{
return $a['id'] == $b['id'] ? 0 : -1;
}
$arrdiff = array_udiff($zones_array1, $zones_array2, 'udiffCompare');
echo '<pre>';
print_r($arrdiff);
array_udiff() compares each element of the first array-argument against all the elements of the second array-argument using the provided callback function. If the callback returns zero for any of the comparisons then the element of the array in the first argument will not be present in the returned array of the function.
You will try it :
function unique_multidim_array($array, $key){
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val){
if(!in_array($val[$key],$key_array)){
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$zones_array1 = array_merge($zones_array2, $zones_array3);
$zones_array1 = unique_multidim_array($zones_array1, 'id');
print_r($zones_array1);
Please try this
array_push($zones_array1,$zones_array2);
print_r(array_unique($zones_array1));
I am not sure.
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 am trying to make and return json data using codeigniter. I want to receive that data in this format
[
{
'title': 'this is title',
'desc': 'THis is desc'
},
{
'title': 'this is title',
'desc': 'THis is desc'
}
]
But I am receiving it this way
[[{"title":"this is title","desc":"this is desc"}],[{"title":"this is title","description":"this is desc"}]]
how can I change this format to above one?
here is my code
public function v1 () {
$this->load->model('model_jokes');
$jokes = $this->model_jokes->readJokes();
$arr = array();
foreach ($jokes as $joke) {
$arr[] = array(
array(
'title' => $joke->title,
'description' => $joke->joke
)
);
}
echo json_encode($arr);
}
Make the assignment inside foreach as
$arr[] = array(
'title' => $joke->title,
'description' => $joke->joke
);
Otherwise you will get a multi-dimensional array for each $joke.
You are adding array of array element each time in a loop. Instead just add single array.
public function v1 () {
$this->load->model('model_jokes');
$jokes = $this->model_jokes->readJokes();
$arr = array();
foreach ($jokes as $joke) {
$arr[] = array(
'title' => $joke->title,
'description' => $joke->joke
);
}
echo json_encode($arr);
}
Try :
echo '<pre>'.json_encode($arr).'</pre>';
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 );