This is my array and i want to convert this as json and added to the database
Array(
[0] => Array
(
[id] => e4da3b7fbbce2345d7772b0674a318d5
[channel] => Array
(
[0] => 1
[1] => 2
)
)
)
I want to store data like this where id remain same and channel will add to the next json bracket with same id
[{"id":"e4da3b7fbbce2345d7772b0674a318d5","channel":1},{"id":"e4da3b7fbbce2345d7772b0674a318d5","channel":2}]
Code
$var1 = array([
'id' => $hash_user,
'channel' => $channel
]);
// print_r($var1);
foreach($var1 as $id){
$encode_data = $id['id'] . $id['channel'][0]. $id['id'] . $id['channel'][1];
$see = json_encode($encode_data);
}
print_r($see);
print_r($encode_data);
//
die;
$info['user_hash'] = $encode_data;
You should be clear in your post. But given the information, I assume you need to change the array you have to that JSON.
What you have:
$databaseArray = [[ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => [1,2]]];
$json = json_encode($databaseArray);
What you want:
$databaseArray = [[ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => 1]];
$json = json_encode($databaseArray);
What you need to change:
$databaseArray = [
[ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => [1,2]],
[ "id" => "1235437fbbce2345d7772b0674a32342", "channel" => [1,2]]
];
$databaseMergedArray = [];
// You need to set the channel to a value instead of array.
foreach($databaseArray as $key => $item) {
foreach($databaseArray[$key]["channel"] as $channel) {
$item["channel"] = $channel;
$databaseMergedArray[] = $item;
}
}
$json = json_encode($databaseMergedArray);
echo ($json);
Related
I have a Curl query which outputs JSON as $response
$response = curl_exec($curl);
$response = json_decode($response, true);
I have turned this into the below Array:
Array
(
[results] => Array
(
[0] => Array
(
[jobId] => 41682277
[employerId] => 630007
[employerName] => ABC
[employerProfileId] =>
[employerProfileName] =>
[jobTitle] => Internal Sales Negotiator/Sales Executive
How can I loop through this array, to show each job on a website. I need to turn some of the fields into variables, for example, jobTitle
I have tried the below but nothing is output back;
foreach ($response as $job) {
foreach ($job->results as $record) {
$ID = $record->jobId;
echo"JobID= $ID<br>";
}
}
According to your array structure, the following code snippet should do the trick. You decode your JSON payload as an associative array by adding the second argument of true to the json_decode function, so it shouldn't being accessed as an object.
<?php
$response = [
'results' => [
[
'jobId' => 41682277,
'employerId' => 630007,
'employerName' => 'employerName',
'employerProfileId' => '',
'employerProfileName' => 'employerProfileName',
'jobTitle' => 'Internal Sales Negotiator/Sales Executive',
],
],
];
foreach ($response['results'] as $record) {
$id = $record['jobId'];
echo "JobID = $id<br>";
}
I need to perform iterated explosions on values in one column of my two dimensional array, then re-group the data to flip the relational presentation from "tag name -> video id" to "video id -> tag name".
Here is my input array:
$allTags = [
[
"name" => "TAG-ONE",
"video" => "64070,64076,64110,64111",
],
[
"name" => "TAG-TWO",
"video" => "64070,64076,64110,64111",
],
[
"name" => "TAG-THREE",
"video" => "64111",
]
];
I want to isolate unique video ids and consolidate all tag names (as comma-separayed values) that relate to each video id.
Expected output:
$allTagsResult = [
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64070",
],
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64076",
],
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64110",
],
[
"name" => "TAG-ONE,TAG-TWO,TAG-THREE",
"video" => "64111",
],
];
Somehow I did it by checking the value using nested loops but I wish to know if you guys can suggest any shortest method to get the expected output.
If you want to completely remove foreach() loops, then using array_map(), array_walk_recursive(), array_fill_keys() etc. can do the job. Although I think that a more straightforward answer using foreach() would probably be faster, but anyway...
$out1 = array_map(function ($data) {
return array_fill_keys(explode(",", $data['video']), $data['name']); },
$allTags);
$out2 = [];
array_walk_recursive( $out1, function ( $data, $key ) use (&$out2) {
if ( isset($out2[$key])) {
$out2[$key]['name'] .= ",".$data;
}
else {
$out2[$key] = [ 'name' => $data, 'video' => $key ];
}
} );
print_r($out2);
will give...
Array
(
[64070] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64070
)
[64076] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64076
)
[64110] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64110
)
[64111] => Array
(
[name] => TAG-ONE,TAG-TWO,TAG-THREE
[video] => 64111
)
)
if you want to remove the keys, then
print_r(array_values($out2));
The code could be compressed by piling all of the code onto single lines, but readability is more useful sometimes.
Another method if you don't like looping:
$video_ids = array_flip(array_unique(explode(",",implode(",",array_column($allTags,'video')))));
$result = array_map(function($id){
return ['name' => '','video' => $id];
},array_flip($video_ids));
array_walk($allTags,function($tag_data) use (&$result,&$video_ids){
$ids = explode(",",$tag_data['video']);
foreach($ids as $id) $result[$video_ids[$id]]['name'] = empty($result[$video_ids[$id]]['name']) ? $tag_data['name'] : $result[$video_ids[$id]]['name'] . "," . $tag_data['name'];
});
Demo: https://3v4l.org/vlIks
Below is one way of doing it.
$allTags = [
'0' => [
"name" => "TAG-ONE",
"video" => "64070,64076,64110,64111",
],
'1' => [
"name" => "TAG-TWO",
"video" => "64070,64076,64110,64111",
],
'2' => [
"name" => "TAG-THREE",
"video" => "64111",
]
];
$allTagsResult = array();
$format = array();
foreach( $allTags as $a ) {
$name = $a['name'];
$videos = explode(',', $a['video']);
foreach( $videos as $v ) {
if( !isset( $format[$v]) ) {
$format[$v] = array();
}
$format[$v][] = $name;
}
}
foreach( $format as $video => $names) {
$allTagsResult[] = array('name' => implode(',', $names), 'video' => $video);
}
echo '<pre>';
print_r($allTagsResult);
die;
You can check Demo
I am typically in favor of functional style coding, but for this task I feel it only serves to make the script harder to read and maintain.
Use nested loops and explode the video strings, then group by those video ids and concatenate name strings within each group. When finished iterating, re-index the array.
Code: (Demo)
$result = [];
foreach ($allTags as $tags) {
foreach (explode(',', $tags['video']) as $id) {
if (!isset($result[$id])) {
$result[$id] = ['video' => $id, 'name' => $tags['name']];
} else {
$result[$id]['name'] .= ",{$tags['name']}";
}
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'video' => '64070',
'name' => 'TAG-ONE,TAG-TWO',
),
1 =>
array (
'video' => '64076',
'name' => 'TAG-ONE,TAG-TWO',
),
2 =>
array (
'video' => '64110',
'name' => 'TAG-ONE,TAG-TWO',
),
3 =>
array (
'video' => '64111',
'name' => 'TAG-ONE,TAG-TWO,TAG-THREE',
),
)
How can I add to a multidimensional array also the index number of the current added item?
$data_array[] = array('data_array_index' => *the index number of the this array on $data_array*, 'stuff' => 'stuff', etc.)
So when I:
print_r($data_array);
Array(
[0] => Array(
data_array_index => 0
stuff => stuff
)
[25] => Array(
data_array_index => 25
stuff => stuff
)
etc.
Thank you
EDIT
Should this work?
$data_array[] = array('data_array_index' => end($data_array)+1, 'stuff' => 'stuff', etc.)
You could do this:
$array = [
0 => [ "data_array_index" => 0, "stuff" => "stuff" ],
25 => [ "data_array_index" => 25, "stuff" => "stuff" ]
];
$array[] = array('data_array_index' => 0, 'stuff' => 'stuff')
end($array);
$last_id = key($array);
$array[$last_id]['data_array_index'] = $last_id;
I don't know why you want data_array_index in the array because if you put it in a foreach loop you can get the key without needing the variable.
Example:
foreach($key => $data) {
^^^^ The same as `data_array_index`
}
Suppose you have this array:
$data_array = [
0 => [ "data_array_index" => 0, "stuff" => "stuff" ],
25 => [ "data_array_index" => 25, "stuff" => "stuff" ]
];
Now to set a key (note the $data_array[100]):
$data_array[100] = [ "data_array_index" => 100, "stuff" => "stuff" ];
try this once
$arr=array(12=>array("stuff"=>"stuff1"),15=>array("stuff"=>"stuff2"));
foreach($arr as $key=>$val){
$arr[$key]['data_array_index']=$key;
}
echo "<pre>"; print_r($arr);
For my solution see the code below. Beware that this is a very rudimentary function now. It does not provide any fail safe or fallback. If you delete a key it will to fill the space etc.
<?php
// data array
$data_array = [];
// additional info for the array
$info_a = "Lorem Ipsum";
$info_b = "Lorem Ipsum";
// call function
addElement($data_array, $info_a);
addElement($data_array, $info_b);
// display output
echo '<pre>';
print_r($data_array);
echo '</pre>';
function addElement(&$array, $info)
{
// add info to the array
$array[] = [
'stuff'=>$info
];
// get the key of the current array
end($array);
$key = key($array);
// add this information to the array
$array[$key]['data_array_index'] = $key;
}
?>
Output would be
Array
(
[0] => Array
(
[stuff] => Lorem Ipsum
[data_array_index] => 0
)
[1] => Array
(
[stuff] => Lorem Ipsum
[data_array_index] => 1
)
)
Use array_walk
array_walk($data_array,function($value,$key)use($new_array) {
$value['data_array_index'] = $key;
$new_array[$key]=$value;
});
working demo: http://phpfiddle.org/main/code/p937-7cue
I have an array that looks like this:
[0] => Array
(
[name] => typeOfMusic
[value] => this_music_choice
)
[1] => Array
(
[name] => myMusicChoice
[value] => 9
)
[2] => Array
(
[name] => myMusicChoice
[value] => 8
)
I would like to reform this into something with roughly the following structure:
Array(
"typeOfMusic" => "this_music_choice",
"myMusicChoice" => array(9, 8)
)
I have written the following but it doesn't work:
foreach($originalArray as $key => $value) {
if( !empty($return[$value["name"]]) ){
$return[$value["name"]][] = $value["value"];
} else {
$return[$value["name"]] = $value["value"];
}
}
return $return;
I've tried lots of different combinations to try and get this working. My original array could contain several sets of keys that need converting to arrays (i.e. it's not always going to be just "myMusicChoice" that needs converting to an array) ?
I'm getting nowhere with this and would appreciate a little help. Many thanks.
You just need to loop over the data and create a new array with the name/value. If you see a repeat name, then change the value into an array.
Something like this:
$return = array();
foreach($originalArray as $data){
if(!isset($return[$data['name']])){
// This is the first time we've seen this name,
// it's not in $return, so let's add it
$return[$data['name']] = $data['value'];
}
elseif(!is_array($return[$data['name']])){
// We've seen this key before, but it's not already an array
// let's convert it to an array
$return[$data['name']] = array($return[$data['name']], $data['value']);
}
else{
// We've seen this key before, so let's just add to the array
$return[$data['name']][] = $data['value'];
}
}
DEMO: https://eval.in/173852
Here's a clean solution, which uses array_reduce
$a = [
[
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
],
[
'name' => 'myMusicChoice',
'value' => 9
],
[
'name' => 'myMusicChoice',
'value' => 8
]
];
$r = array_reduce($a, function(&$array, $item){
// Has this key been initialized yet?
if (empty($array[$item['name']])) {
$array[$item['name']] = [];
}
$array[$item['name']][] = $item['value'];
return $array;
}, []);
$arr = array(
0 => array(
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
),
1 => array(
'name' => 'myMusicChoice',
'value' => 9
),
2 => array(
'name' => 'myMusicChoice',
'value' => 8
)
);
$newArr = array();
$name = 'name';
$value = 'value';
$x = 0;
foreach($arr as $row) {
if ($x == 0) {
$newArr[$row[$$name]] = $row[$$value];
} else {
if (! is_array($newArr[$row[$$name]])) {
$newArr[$row[$$name]] = array();
}
array_push($newArr[$row[$$name]], $row[$$value]);
}
$x++;
}
Here are two example of the format of the Arrays, full code and array content in my code below.
ARRAY 1
[
'version' => '1.0',
'injuries' => [
'timestamp' => 1377702112,
'week' => 1,
'injury' => [
[
'status' => 'Questionable',
'id' => '10009',
'details' => 'Shoulder'
],
[
'status' => 'Questionable',
'id' => '10012',
'details' => 'Ankle'
]
]
]
]
ARRAY 2
[
'version' => '1.0',
'players' => [
'timestamp' => 1377676937,
'player' => [
[
'position' => 'TMDL',
'name' => 'Bills, Buffalo',
'id' => '0251',
'team' => 'BUF'
],
[
'position' => 'TMDL',
'name' => 'Colts, Indianapolis',
'id' => '10009',
'team' => 'IND'
]
]
]
]
What I need to do is sort through both Arrays and finding matching values for the ID key. I need to then combine the values of both arrays into one array so I can print it out on screen. There is two API's provided, one for the injuries report with a player [id] key and the other for the Players Information with [id] keys. Here is how far I have gotten on this problem:
<?php
function injuries_report() {
//Get json files
$injuryData = file_get_contents('http://football.myfa...=1&callback=');
$playerData = file_get_contents('http://football.myfa...L=&W=&JSON=1');
//format json data into an array
$obj1 = json_decode($injuryData, true);
$obj2 = json_decode($playerData, true);
//return print_r($obj1); //print obj1 to see output
return print_r($obj2); //print obj2 to see output
}
?>
<!--get injuries report -->
<pre><?php injuries_report(); ?></pre>
Here's the working code, thanks to Chris:)
$injuryData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=injuries&L=&W=&JSON=1&callback=');
$array1 = json_decode($injuryData, true);
$playerData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=players&L=&W=&JSON=1');
$array2 = json_decode($playerData, true);
function map($x) {
global $array1;
if(isset($x['id'])) {
$id = $x['id'];
$valid = array_filter($array1['injuries']['injury'], create_function('$injury', 'return $injury["id"] == "' . $id .'";'));
if(count($valid) > 0) {
$x = array_merge($x, array_shift($valid));
}
}
return $x;
}
$output = array_map('map', $array2['players']['player']);
echo "<pre>";
print_r($output);
echo "</pre>";
Ok, I'm assuming you want to add injuries to players. The output will be the list of players, with the injuries added (where they apply)
$output = array_map(function($x) use ($array1) {
$id = $x['id'];
$valid = array_filter($array1['injuries']['injury'], function($injury) use ($id) {
return $injury['id'] == $id;
});
if(count($valid) > 0) {
$x = array_merge($x, $valid[0]);
}
return $x;
}, $array2['players']['player']);
print_r($output);
The output is this:
Array
(
[0] => Array
(
[position] => TMDL
[name] => Bills, Buffalo
[id] => 0251
[team] => BUF
)
[1] => Array
(
[position] => TMDL
[name] => Colts, Indianapolis
[id] => 10009
[team] => IND
[status] => Questionable
[details] => Shoulder
)
)
php 5.2
Edit The latest working version:
Oh you are using php 5.2. Here is a php 5.2 version, but it less pretty than the code before:
$injuryData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=injuries&L=&W=&JSON=1&callback=');
$array1 = json_decode($injuryData, true);
$playerData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=players&L=&W=&JSON=1');
$array2 = json_decode($playerData, true);
function map($x) {
global $array1;
if(isset($x['id'])) {
$id = $x['id'];
$valid = array_filter($array1['injuries']['injury'], create_function('$injury', 'return $injury["id"] == "' . $id .'";'));
if(count($valid) > 0) {
$x = array_merge($x, array_shift($valid));
}
}
return $x;
}
$output = array_map('map', $array2['players']['player']);
print_r($output);
The $array1 is global here. Check it here: http://pastebin.com/N3RqtfzN