I've been searching around quite a bit for an answer for this, but I'm afraid that I've been unable to figure out a solution to this problem. I've created a multidimensional array which includes zip code information. However, I've been unable to pull the values out of it in the way that I need to. Here's an example of the print_r():
Array (
[0] => Array (
[0] => 59101
[1] => 0.0 )
[1] => Array (
[0] => 59102
[1] => 5.0 )
[2] => Array (
[0] => 59105
[1] => 6.8 )
[3] => Array (
[0] => 59106
[1] => 9.2 )
[4] => Array (
[0] => 59037
[1] => 12.7 )
[5] => Array (
[0] => 59044
[1] => 13.9 )
[6] => Array (
[0] => 59002
[1] => 16.6 )
[7] => Array (
[0] => 59079
[1] => 19.3 )
)
I need to look through the array for a specific zip code, and then get distance (the second value in each array) associated with that zip code. I'd considered restructuring the array, but I'm unsure of how to accomplish it. Here's my current code:
EDIT## sorry, I may not have been clear. The below code is what I'm using to build the array, not to extract information from the array. I have not idea how to get the information out of the array.
$rArray = array();
foreach ($points as $point){
$zips = $point->Postcode;
$dists = number_format($point->D,1);
array_push($rArray,array($zips,$dists));
}
Any thoughts on the best way to accomplish this? Thanks!
This?
EDIT: After your question update.
function getDistanceByZip($zip) {
$array = //your array here;
foreach($array as $value) {
if($zip == $value[0]) {
return $value[1];
}
}
return false;
}
Maybe this?
foreach ($points as $point){
if ($point->Postcode === $codeIamLookingFor) {
echo "Distance: " . number_format($point->D, 1);
}
}
function arrayseek($array, $zip){
foreach($array as $k => $v){
if($v[0] == $zip){
return $v[1];
}
}
return false;
}
Related
I apologize if this is a very simple question - I've read through tons of posts here, but my question is syntactically very hard to search for, so I haven't found an answer yet.
I have a json array that's output from a company's API:
[Result] => Array
(
[cData] => Array
(
[0] => Array
(
[Reqa] => ABCD
[Reqb] =>
[Reqc] => Plus
[dto] => Array
(
[0] => Array
(
[ComID] => 43292392
[Comment] => Dave
)
[1] => Array
(
[ComID] => 43292392
[Comment] => Bob
)
)
[XREFSearchOperation] => Exact
)
[1] => Array
(
[Reqa] => BCDE
[Reqb] =>
[Reqc] => A
[dto] => Array
(
[0] => Array
(
[ComID] => 19331186
[Comment] => Mike
)
[1] => Array
(
[ComID] => 19331186
[Comment] => Roger
)
)
[XREFSearchOperation] => Starts With
)
[2] => Array
(
[Reqa] => QQDT
[Reqb] =>
)
)
)
)
and I'm trying to access the [ComID] and [Comment] elements, if they exist, inside of a foreach loop and assign it to the variable $y
So far I have:
foreach ($json['Result']['cData']['dto'] as $i) {
$y = "{$i['ComID']}|{$i['Comment']}";
}
but this gives me zero results. I understand WHY, because in between ['cData'] and ['dto'] are [0], [1], [2] etc.. elements, and I don't know how to add a qualifier for those into the loop.
Update
This code works for most of the json response:
foreach ($json['Result']['cData'] as $i) {
if(array_key_exists('dto', $i)) {
foreach ($i['dto'] as $j) {
$y = "{$j['ComID']}|{$j['Comment']}";
} else {
}
}
However - I'm having one more small issue. If there are multiple [dto] responses, you'll have [dto][0][ComID] then [dto][1][ComID] and [dto][2][ComID], (like in the example above,) but if there's only ONE response, you'll have [dto][ComID] as there's no need for that middle array.
I tried writing if(array_key_exists('dto[0]' to execute one, then an else statement in the event dto[0] doesn't exist, but that didn't work. I need a way of NOT executing a foreach loop if there is no array underneath it to "foreachicize". Is there an if/else statement I can write to accommodate this?
Probably need a nested foreach:
foreach ($json['Result']['cData'] as $i) {
foreach($i['dto'] as $j) {
$y[] = "{$j['ComID']}|{$j['Comment']}"; //need an array here
}
}
For the update to the question. Check if $i['dto'][0] exists:
foreach ($json['Result']['cData'] as $i) {
if(isset($i['dto'][0]))) {
foreach($i['dto'] as $j) {
$y[] = "{$j['ComID']}|{$j['Comment']}";
}
} else {
$y[] = "{$j['ComID']}|{$j['Comment']}";
}
}
There might be a better way but I'm headed out.
Another approach:
foreach($json['Result']['cData'] as $cData)
{
foreach($cData['dto'] as $dto)
{
if(array_key_exists('ComID', $dto) && array_key_exists('Comment', $dto))
{
$y = "{$dto['ComID']}|{$dto['Comment']}";
}
}
}
I know this is a newbie question,
I extracted some preformatted json out of javascript, that looks like this:
[[[455837.99,2896882.36],[455862.44,2896888.35],[455868.79,2896860.14],[455864.3,2896852.78],[455845.76,2896848],[455837.99,2896882.36]]]
I tried an online formatted that shows me the array looks something like this:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 455837.99
[1] => 2896882.36
)
[1] => Array
(
[0] => 455862.44
[1] => 2896888.35
)
[2] => Array
(
[0] => 455868.79
[1] => 2896860.14
)
[3] => Array
(
[0] => 455864.3
[1] => 2896852.78
)
[4] => Array
(
[0] => 455845.76
[1] => 2896848
)
[5] => Array
(
[0] => 455837.99
[1] => 2896882.36
)
)
)
All the third [0]'s are what I need as an X, so everything that starts with 455. and All the [1]'s are the Y's. I would like these two to be grouped together, the respective X and Y.
My problem is I am not sure how to access them out of the area, I have tried this:
preg_match_all('/\[{3}.*\]{3}/', $data, $matches);
$arr=array();
foreach ($matches[0] as $match)
{
$arr[]=json_decode($match);
}
echo '<br>';
$newmatch = json_decode($match);
I would really appreciate if someone can point me in the direction of being able to have a loop that basically echo's the X and Y values, whenever I try and echo something from the array I get:
1) Array to string conversion
I am not sure if that is because of the triple brackets, that its an array in an array in an array.
$data = "[[[455837.99,2896882.36],[455862.44,2896888.35],[455868.79,2896860.14],[455864.3,2896852.78],[455845.76,2896848],[455837.99,2896882.36]]]";
$data_array = json_decode($data);
if (is_array($data_array) && array_key_exists(0, $data_array)) {
foreach ($data_array[0] as $element) {
$x = array_key_exists(0, $element) ? $element[0] : "N/A";
$y = array_key_exists(1, $element) ? $element[1] : "N/A";
printf("X: %s | Y: %s\n", $x, $y);
}
}
I'm trying to experiment with array_splice and I get an output like this (from $match)
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
)
[0] => valuel.jpg //this should really be inside [Leep me Updated] array
[1] => value2.jpg //this should really be inside [Leep me Updated] array
[2] => value3.jpg //this should really be inside [Leep me Updated] array
}
from (this foreach creates puts in the values into $match)
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match,1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}
What I'm trying to get is bring [0],[1],[2] into the [Keep me Updated] $match array:
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
[1] => value1.jpg // old one: [0] => valuel.jpg
[2] => value2.jpg // old one: [1] => value2.jpg
[3] => value3.jpg // old one: [2] => value3.jpg
)
}
This is what $data looks like
$data[] = array(
"data"=>array
(
"name"=>$name,
),
"winner"=>array
(
"lrg_img"=>$img_url_winner
),
"loser"=>array
(
"lrg_img"=>$img_url_loser
)
$data has array values, and $match is where I'm trying to sort the data. So if my values match, it'll consolidate.
Thanks!
Use the inner array as the argument to array_splice
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match[$d['data']['name']],1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}
So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}
I've "inherited" some data, which I'm trying to clean up. The array is from a database which, apparently, had no keys.
The array itself, is pretty long, so I'm simplifying things for this post...
[0] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[ename] => Standard
[eaction] => Check
)
[1] => Array
(
[id] => 2
[uid] => 110
[eid] => 8
[ename] => Standard
[eaction] => Check
)
[2] => Array
(
[id] => 2
[uid] => 200
[eid] => 8
[ename] => Standard
[eaction] => Check
)
I'm trying to shift things around so the array is multidimensional and is grouped by ename:
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
Anyone know how to do something like this?
You can use usort() to sort an array by a user-defined function. That function could compare the ename fields. Then it's just a simple transformation. Like:
usort($array, 'cmp_ename');
function cmp_ename($a, $b) {
return strcmp($a['ename'], $b['ename']);
}
and then:
$output = array();
foreach ($array as $v) {
$ename = $v['ename'];
unset($v['ename']);
$output[] = array($ename => $v);
}
$outputarray = array();
foreach($inputarray as $value) {
$outputarray[] = array($value['ename'] => $value);
}
would accomplish what your examples seem to indicate (aside from the fact that your 'result' example has multiple things all with key 0... which isn't valid. I'm assuming you meant to number them 0,1,2 et cetera). However, I have to wonder what benefit you're getting from this, since all it appears to be doing is adding another dimension that serves no purpose. Perhaps you could clarify your example if there are other things to take into account?
$outputarray = array();
foreach($inputarray as &$value) {
$outputarray[][$value['ename']] = $value;
unset($value['ename']);
} unset($value);
I'm guessing that this is what you're asking for:
function array_group_by($input, $field) {
$out = array();
foreach ($input as $row) {
if (!isset($out[$row[$field]])) {
$out[$row[$field]] = array();
}
$out[$row[$field]][] = $row;
}
return $out;
}
And usage:
var_dump(array_group_by($input, 'ename'));
philfreo was right but he was also off a little. with his code every time you encounter an array element with an ['ename'] the same as one you've already gone through it will overwrite the data from the previous element with the same ['ename']
you might want to do something like this:
$output = array();
foreach ($YOURARRAY as $value) {
$output[$value['ename']][] = $value;
}
var_dump($output); // to check out what you get