PHP Striping/Exporting single strings from an array - php

I have an array, like this:
)array (
'date' => '2015-12-10T00:16:58+0000',
'from' =>
array (
'name' => 'Joe Bloggs',
'user_id' => 3220562,
),
'message' => ':ip=1.1.1.1',
)
And here's my code:
$string = var_export($h, true);
echo $string;
And finally, here's what I would like to achieve:
I would like to export single strings from the array (for example I want to export 'message', and then I would get an output of ":ip=1.1.1.1").
I have tried things like $h['message'] and this doesn't work, so I'm just wondering what's the easiest / cleanest way to do this.
Any help would be greatly appreciated.

Related

PHP - How do I add a name to an array

I am building an array (json encoded) and returning it to the caller. My output currently looks like this:
[{"org_id":1,"org_name":"Org 1"},{"org_id":4,"org_name":"Org 4"}]
I want to add a name so that output looks like this:
{
“orgs” : [
{"org_id":1,"org_name":"Org 1"},
{"org_id":4,"org_name":"Org 4"}
]
}
Here is my current code:
// if orgs were found then
if ( is_array($orgs) && !empty($orgs) ) {
$json_orgs = json_encode($user_orgs);
// else return an empty array
} else {
$user_orgs = array();
}
I am fairly new to OO coding, so I have not figured out how to initialize an object so that "orgs" is present. Maybe I don't even need an object. Any help would be greatly appreciated.
Before you json encode the array, just wrap it in another one:
$newArray = ['orgs' => $yourCurrentArray];
Then you json encode the new variable instead.
If you rather not create a new array, you can simply do:
json_encode(['orgs' => $yourCurrentArray]);
This doesn't really have anything to do with OOP since you're just working with arrays. Associative arrays becomes objects when encoded into JSON.
You didn't say exactly how you're generating the JSON at the moment, or from what object/variable in PHP, or with what structure (there is more than one possible way).
But in general, here's how you could do it with an associative array:
$data = array (
'orgs' =>
array (
0 =>
array (
'org_id' => 1,
'org_name' => 'Org 1',
),
1 =>
array (
'org_id' => 4,
'org_name' => 'Org 4',
),
),
)
And then json_encode that to get the JSON.
(Hint: you can simply do the process in reverse to generate this example code from the desired JSON.)
You can achieve this by adding a key, for example:
// variable holding your data
$data;
// return statement in your controller
return ['orgs' => $data];
You just need to decode this with json_decode() and then you get like this
array (
0 =>
array (
'org_id' => 1,
'org_name' => 'Org 1',
),
1 =>
array (
'org_id' => 4,
'org_name' => 'Org 4',
),
)
then you need to add parant array on it
array( "orgs"=> array (
0 =>
array (
'org_id' => 1,
'org_name' => 'Org 1',
),
1 =>
array (
'org_id' => 4,
'org_name' => 'Org 4',
),
)
)
then again encode it and you will get your answer

How do I reference an element of an "unamed" array?

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()

String to array conversion if string has content like an array

I have something like this:
array('fields' => array(
0 => array('name' => 'family_name',
'label' => 'Family Names'),
array('name' => given_names',
'label' => 'Given Names'),
array('name' => 'additional_names',
'label' => 'Additional Names'),
array('name' => 'honorific_prefixes',
'label' => 'Honorific Prefixes'),
array('name' => honorific_suffixes',
'label' => 'Honorific Suffixes')
)
)
in a variable as string. The whole thing is in one database field. If I output the variable, it is a string.
I would have an array with the content as subarrays. How do I convert this value into an array?
I searched with google, but I found explode and split and so on, but I think I miss the key word to find any solution.
Thank you for any help in this case.
Try using eval(), https://secure.php.net/manual/en/function.eval.php
eval("\$array = $string;");
print_r($array);
Your string is not built correctly to put it into the eval function. Two strings inside don't have the preceding quote and that will lead to a parse error. But you can correct it with:
$string = str_replace("=> given_names'", "=> 'given_names'", $string);
$string = str_replace("=> honorific_suffixes'", "=> 'honorific_suffixes'", $string);
After that you can use the answer of shapeshifter (please mark his answer as the correct one):
eval("\$array = $string;");
var_dump($array);
If you just look for a method to save and restore your arrays you could also use serialize / unserialize.

PHP json_encode won't output proper result

I want to output users via a json object but when I try to output their songs list it only outputs the last one. I want to get this list into an array.
this is my array push while looping through users,
array_push($arrayUsers, array(
'username' => $user['username'],
'id' => $user['_id'],
'favSongs' => array(
'title' =>'song1',
'title' =>'song2'
)
)
);
but this is what I get back (missing song title),
[{"username":"asdfasdfasd","id":{"$id":"4f58d7227edae19c02000000"},"songs":{"title":"song2"}}]
I want it to output the songs like this, but am confused how to get it to do this using PHP:
"songs":[{"title": "song1"}, {"title": "song2"}]
'favSongs' => array(
'title' => 'song1',
'title' => 'song2'
)
PHP will replace the 'title' key with the last one declared.
"songs":[{"title": "song1"}, {"title": "song2"}]
This is an array of objects, so in PHP it needs to be an array of arrays.
'favSongs' => array(
array('title' => 'song1'),
array('title' => 'song2')
)

PHP / Mongo: how do you update nested data?

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.

Categories