Retrieve single value from this php array - php

I have this php array $result2 that looks like this.
[
(int) 0 => object(stdClass) {
id => (int) 1
username => 'asd'
password => '123'
fullname => 'asd'
email_addr => 'asd#gmail.com'
}
]
From $result2, I want to have a $json_result that looks like this;
[{"email_addr":"asd#gmail.com"}]
I tried
$emailAddress[] = ['email_addr' => $result2['email_addr'] ];
echo json_encode($emailAddress);
However, the error I get is this;
Notice (8): Undefined index: email_addr
[APP/Controller\DeptUsersController.php, line 126]
The output is like this which is wrong;
[{"email_addr":null}]
What is the correct way?

Read carefully (int) 0 => object(stdClass) It's an object, and this object is an element with index 0 of an array. So:
$emailAddress[] = ['email_addr' => $result2[0]->email_addr ];

it's object you can't show value if using $result2['email_addr'] you should using this $result2->email_addr method

You have an object of type stdClass so you can't access directly to the field email_addr. Try this code:
$mObject = new stdClass();
$mObject = $result2[0];
$emailAddress[] = ['email_addr' => $mObject->email_addr ];
echo json_encode($emailAddress);
This should fix your error

Try this:
$emailAddress[] = ['email_addr' => $result2[0]->email_addr ];

You can use array_intersect_key :
$wanted = ["email_addr"=>""];
$data = [
"id" => 1,
"username" => 'asd',
"password" => '123',
"fullname" => 'asd',
"email_addr" => 'asd#gmail.com',
];
$result = array_intersect_key($wanted, $data);
var_dump($result);
It useful when you need one or more key to find. It more saving time

Related

Php key is undefined, but there is key

I am making my own array from another one, using email field as key value. If there is more results with same email I am amking array_push to existing key.
I am getting always data in my array (with email) and here is the example
Input data
Example data
$saved_data = [
0 => ['custom_product_email' => 'test#test.com',...],
1 => ['custom_product_email' => 'test#test.com',...],
2 => ['custom_product_email' => 'bla#test.com',...],
3 => ['custom_product_email' => 'bla#test.com',...],
...
];
Code
$data = [];
foreach ($saved_data as $products) {
$curVal = $data[$products->custom_product_email];
if (!isset($curVal)) {
$data[$products->custom_product_email] = [];
}
array_push($data[$products->custom_product_email], $products);
}
Error
I am getting error Undefined index: test#test.com and if I debug my array, there is key with value of 'test#test.com', so key is defined (!)
so var $curVal key is undefined
Result
So the goal of foreach is to filter all objects in array with same email, here is the example:
$data = [
'test#test.com' => [
0 => {data},
1 => {data},
...
],
'bla#test.com' => [
0 => {data},
1 => {data},
...
],
];
this line $curVal = $data[$products->custom_product_email]; is useless and is the one provoking the error: you just initialized $data as an empty array, logically the index is undefined.
You should test directly if (!isset($data[$products->custom_product_email])) {
Then explanation: there is a fundamental difference between retreiving the value of an array's index which is undefined and the same code in an isset. The latter evaluating the existence of a variable, you can put inside something that doesn't exist (like an undefined array index access). But you can't store it in a variable before the test.
Did you not see the error message?
Parse error: syntax error, unexpected '{' in ..... from this code
$saved_data = [
0 => {'custom_product_email' => 'test#test.com',...},
1 => {'custom_product_email' => 'test#test.com',...},
2 => {'custom_product_email' => 'bla#test.com',...},
3 => {'custom_product_email' => 'bla#test.com',...},
...
];
Change the {} to [] to correctly generate the array.
$saved_data = [
0 => ['custom_product_email' => 'test#test.com',...],
1 => ['custom_product_email' => 'test#test.com',...],
2 => ['custom_product_email' => 'bla#test.com',...],
3 => ['custom_product_email' => 'bla#test.com',...],
...
];
Your next issue is in this code
$data = [];
foreach ($saved_data as $products) {
$curVal = $data[$products->custom_product_email];
// ^^^^^
$data is an empty array that you initialised 2 lines above, so it does not contain any keys or data!
Check, if $data[$products->custom_product_email] is already set in $data array
Try This code
$data = [];
foreach ($saved_data as $products) {
$curVal = isset($data[$products->custom_product_email]) ? $data[$products->custom_product_email] : null;
if (!isset($curVal)) {
$data[$products->custom_product_email] = [];
}
array_push($data[$products->custom_product_email], $products);
}

How to put array to obj in php?

I have an json obj:
$response["data"][] = array("ID" => $comment["ID"]);
I put to new obj like this:
array_push($response["username"],"abc");
and it return like this:
{"data":[{"ID":"2106"}],"username":"123"}
but I want to like this:
{"data":[{"ID":"2106","username":"123"}]}
How can I do it?
Maybe you mean this:
{"data":[{"ID":"2106", "username":"123"}]
BTW you need
array_push($response["data]["username"],"abc");
Maybe you want:
$response["data"][] = array("ID" => $comment["ID"], 'username' => '123');
Please note that you can always simplify your code to make it more readable by creating variables.
$row = array(
'ID' => $comment['ID'],
'username' => '123'
);
$response['data'][] = $row;

Using square brackets and assigning variables in PHP

I have seen source code like:
$something = $sql['value']
I have searched a lot about it and I found that it's from arrays. But I didn’t understand the exact meaning.
For example,
$people = [
'Susan' => [
'Age' => 24,
'Phone' => '555-123-4567'
],
'Jack' => [
'Age' => 27,
'Phone' => '555-9876-5432'
]
];
echo $people['Jack']['Age']; // 27
Can we write code like the following?
if(!empty($people)
$something = $people['a value']
I just need to know how we can declare a variable and give a value in square brackets.
If you are using $something = $people['a value'] it means you are assigning a value of the $people array having an index of a value.
So you don't have that and so it will throw you undefined index error.
You are using a nested associative array and you have to output using something like:
echo $people['Jack']['Age'];
As you wanted a brief example, say you have an array like
$people = array('name'=>'Jack');
Now, when you want to store the name in a variable, you use
$store_name = $people['name'];
echo $store_name; // Echoes "Jack"
Try this:
$people = array(
'Susan' => array('Age' => 24, 'Phone' => '555-123-4567'),
'Jack' => array('Age' => 27, 'Phone' => '555-9876-5432')
);
You can use array and write it like this
$people = array(
'Susan' => array(
'Age' => 24,
'Phone' => '555-123-4567'
),
'Jack' => array(
'Age' => 27,
'Phone' => '555-9876-5432'
)
);
echo $people['Jack']['Age']; // 27
if(!empty($people)
$something = $people['a value']
Square brackets mean index, so $people['a value'] is a value that lays under the 'a value' index of the $people array.
Square brackets are also used as a shortcut for array().. See it here-

How to insert an array to an array

I would like to add an array to within an existing array.
I am tryin to use array_push which works as long as i dont try to assign a key to the array (if i try to add a key i get a syntax error... :-()
This is my initial array:
$ResultArray = array(
"TransactionDate" => "$TransactionDate",
"tx"=>array(
"0"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" => "$PaymentConfirmedCount"
),
"1"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" => "$PaymentConfirmedCount"
)
)
);
i would then like to add:
$ArrayTOAdd = array(
"0"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" =>
"$PaymentConfirmedCount"
)
);
if I try:
array_push($ResultArray->tx, $ArrayTOAdd);
BUT this does not work and results in a warning of "array_push() [function.array-push]: First argument should be an array"
if i try this :
array_push($ResultArray, $ArrayTOAdd);
it just adds the array but not to $ResultArray->tx
Any suggestions would be greatly welcomed!
You have to access the element in the array with $ResultArray["tx"] and not $ResultArray->tx. The second one is for the access to members in a php class. So an
array_push($ResultArray["tx"], $ArrayTOAdd);
should work.

array_push() with key value pair

I have an existing array to which I want to add a value.
I'm trying to achieve that using array_push() to no avail.
Below is my code:
$data = array(
"dog" => "cat"
);
array_push($data['cat'], 'wagon');
What I want to achieve is to add cat as a key to the $data array with wagon as value so as to access it as in the snippet below:
echo $data['cat']; // the expected output is: wagon
How can I achieve that?
So what about having:
$data['cat']='wagon';
If you need to add multiple key=>value, then try this.
$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
$data['cat'] = 'wagon';
That's all you need to add the key and value to the array.
You don't need to use array_push() function, you can assign new value with new key directly to the array like..
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
For Example:
$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');
For changing key value:
$data['firstKey'] = 'changedValue';
//this will change value of firstKey because firstkey is available in array
output:
Array ( [firstKey] => changedValue [secondKey] => secondValue )
For adding new key value pair:
$data['newKey'] = 'newValue';
//this will add new key and value because newKey is not available in array
output:
Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey]
=> newValue )
Array['key'] = value;
$data['cat'] = 'wagon';
This is what you need.
No need to use array_push() function for this.
Some time the problem is very simple and we think in complex way :) .
<?php
$data = ['name' => 'Bilal', 'education' => 'CS'];
$data['business'] = 'IT'; //append new value with key in array
print_r($data);
?>
Result
Array
(
[name] => Bilal
[education] => CS
[business] => IT
)
Just do that:
$data = [
"dog" => "cat"
];
array_push($data, ['cat' => 'wagon']);
*In php 7 and higher, array is creating using [], not ()

Categories