This question already has answers here:
Using an If-else within an array
(10 answers)
Closed 4 years ago.
This is a bit of an odd one. I am building an array in PHP and then encoding it to JSON before I spit it out.
$arr = array (
'reportDescription' =>
array (
if ($queryType == "realtime")
{
'source' => 'realtime',
}
'reportSuiteID' => 'rbsglobretailprod',
'dateGranularity' => $queryGran,
'dateFrom' => $queryFrom,
'dateTo' => $queryTo,
'elements' =>
array (
0 =>
array (
'id' => $queryElement,
),
),
'metrics' =>
array (
0 =>
array (
'id' => $queryMetric,
),
),
),
);
I am trying to get it to add a line to the array if the query type is realtime. This is what I tried but I'm not sure if it's possible to do this, and if it's not, I'm not sure how I should approach it. The error I get below suggests it may not be possible:
Parse error: syntax error, unexpected 'if' (T_IF), expecting ')'
You should do it as two separate calls:
$array = ['your', 'array', 'with', 'fields']
if ($queryType === 'realtime') {
$array[] = ['source' => 'realtime'];
}
Obviously change out the values with your expected values, but that should do the job. You could also append like so if you wanted it at root level:
if ($queryType === 'realtime') {
$array['source'] = 'realtime';
}
Related
I have a large multidimensional array that looks like the below.
I want to remove duplicate arrays based on the ID, however, I am struggling to achieve this.
I want the duplicates to work over the entire array, so you can see that ID 1229873 is a duplicate, in the array 2021-07-07 and 2021-07-09, it should therefore be removed from 2021-07-09
How would I achieve this? array_unique has not worked for me.
$data = array (
'2021-07-07' =>
array (
0 =>
array (
'id' => 5435435,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
1 =>
array (
'id' => 1229873,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
),
'2021-07-09' =>
array (
0 =>
array (
'id' => 3243234,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
1 =>
array (
'id' => 1229873,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
),
);
This is a perfect case for array_uunique()! No wait, scratch that. The PHP devs refused to implement it for the perfectly valid reason of... [shuffles notes] "the function name looks like a typo".
[sets notes on fire]
Anyhow, you just need to iterate over that data, keep track of the IDs you've seen, and remove entries that you've already seen.
$seen = [];
foreach(array_keys($data) as $i) {
foreach(array_keys($data[$i]) as $j) {
$id = $data[$i][$j]['id'];
if( in_array($id, $seen) ) {
unset($data[$i][$j]);
} else {
$seen[] = $id;
}
}
}
I've opted for the foreach(array_keys(...) as $x) approach as avoiding PHP references is always the sane choice.
Run it.
I am Sure That is the way which you want to get the unique array.
$unique = array_map("unserialize", array_unique(array_map("serialize", $data)));
echo "<pre>";
print_r($unique);
echo "</pre>";
I'm using laravel 5.6, and the debugbar allows me to do this:
$IncomingAJAX = json_decode($AJAXrequest, TRUE);
Log::info($AJAXrequest);
which produces this:
[2018-08-05 20:39:11] local.INFO: array (
0 =>
array (
'category' => 'This is Category 1',
'answers' =>
array (
0 =>
array (
'question' => 'This is Question 1',
'score' => 2,
),
1 =>
array (
'question' => 'This is question 2',
'score' => 3,
),
),
),
1 =>
array (
'category' => 'Category #67',
'answers' =>
...
But how do I refer to a specific element? This is driving me mad. I've tried Log::info($AJAXrequest[0].category[0].Answers[0]); and Log::info($IncomingAJAX[0].category[0].Answers[0]); or even just Log::info([0].category[0].Answers[0]) or this one Log::info(AJAXrequest['category']) to no avail.
But this works: Log::info($AJAXrequest[0]['category']);
What I'd really like to do is iterate as follows:
$jsonIterator = new \RecursiveIteratorIterator(
new \RecursiveArrayIterator($AJAXrequest),
\RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
...}
I'm missing something obvious.
It looks like your syntax is incorrect. you are accessing array elements. The dot (.) syntax is invalid in PHP.
Try
$AJAXRequest[0]["category"]
$AJAXRequest[0]["answers"][0]["question"]
$AJAXRequest[0]["answers"][1]["question"]
$AJAXRequest[1]["category"]
...
You need to look into the structure of your array more.
Also, seems like $AJAXRequest is already an array, so no need for json_decode()
I'm trying to remove one value in array and I'm using Unset function, but when I'm passing array in Unset function I got error.
array:
Array ( [mid] => 8 [optionsRadios2] => 0 [optionsRadios3] => 1 [optionsRadios5] => 0 [optionsRadios6] => 0 [optionsRadios7] => 1 [optionsRadios24] => 0 [optionsRadios25] => 1 )
I want to remove mid and I'm using like this:
$module=$data['mid'];
$newdata=unset($data['mid']);
error:
Parse error: syntax error, unexpected 'unset' (T_UNSET) in C:\xampp\htdocs\Traning\application\controllers\home.php on line 77
Please help.
Use only:
unset($data['mid']);
without assign to variable.
In docs unset() return void.
at the first look you code looks ok?
can you check this example http://sandbox.onlinephpfunctions.com/code/b538f88a23433b767005f5a16ca99faa5eb4f8b0
$koko = [
'mid' => 1,
'name' => 'koko'
];
print_r($koko);
echo '---------------------------';
$toto = $koko['name'];
unset($koko['name']);
print_r($koko);
echo 'and your name is : '.$toto;
This question already has answers here:
Forcing a SimpleXML Object to a string, regardless of context
(11 answers)
Closed 8 years ago.
I'm working on storing result of xml feed into database... I'm able to load file... but when I want to store data into array, it stores instead of value ([title] = 'Klapka 120mm';) this:
[title] => SimpleXMLElement Object ( [0] => Klapka 120mm )
Do you know, where might be problem?
Source code:
Here is part of one function:
$import_file = simplexml_load_file($this->input->post('import_url')); // load file from url
$affected_products = 0;
foreach($import_file->SHOPITEM as $product) {
$affected_products += $this->import_product($product);
}
Here is first part of function import_product:
public function import_product($product)
{
/* save product data into array */
$data = array(
'title' => $product->PRODUCT,
'content' => $product->DESCRIPTION,
'price' => $product->PRICE,
'price_vat' => $product->PRICE_VAT,
'ean' => $product->EAN,
'count' => $product->AVAILABILITY
);
die(print_r($data));
Thank you very much for your replies
You have to cast the elements to strings, as all these elements are instances of SimpleXMLElement.
$data = array(
'title' => (string)$product->PRODUCT,
'content' => (string)$product->DESCRIPTION,
'price' => (string)$product->PRICE,
'price_vat' => (string)$product->PRICE_VAT,
'ean' => (string)$product->EAN,
'count' => (string)$product->AVAILABILITY
);
For some of them a cast to an integer or a float may be of interest
I've been playing around with Mongo for about a week now and I still can't work out how to modify nested arrays in Mongo with php.
So here is a sample document...
array (
'_id' => new MongoId("4cb30f560107ae9813000000"),
'email' => 'mo#maurice-campobasso.com',
'firstname' => 'Maurice',
'lastname' => 'Campobasso',
'password' => 'GOD',
'productions' =>
array (
0 =>
array (
'title' => 'a',
'date' => '1286811330.899',
),
1 =>
array (
'title' => 'b',
'date' => '1286811341.183',
),
2 =>
array (
'title' => 'c',
'date' => '1286811350.267',
),
3 =>
array (
'title' => 'd',
'date' => '1286811356.05',
),
),
)
What I wan't to do is delete an array inside the productions array, but I can't work out how. I've been playing with 'update('$pull' => ...etc)' but I haven't been able to make it work.
OK, there are a few ways to do this. In your case, I would do something like
mymongoobject.update( $unset : { "productions.2" : 1 } }
That's basically saying to unset the ".2" element of productions. Some docs here.
Now $pull should also work, but it's a little tougher because "productions" is actually an array of arrays (or objects with sub-objects). So you'd have to match arrays exactly:
mymongoobject.update( $pull : { "productions" : {'title':'d', 'date':'1286811356.05'} }
In the case above, the unset is probably the easiest option (though it will leave a "hole" in the array)
That is actually very easy, unlike traditional sql stuff you just modify the whole data and pass it back.
$cursor = $mongo->yourDB->yourCollection->findOne("_id",4cb30f560107ae9813000000);
//let's remove last item on productions
array_splice($cursor["productions"],2);
//and update the mongo document
echo $mongo->yourDB->yourCollection->update($cursor);
//it echoes 1 if successful
hope it helps.