PHP Display array element - php

Have array
Array (
[3] =>
stdClass Object (
[term_id] => 3
[name] => Lietuviu
[slug] => lietuviu
[term_group] => 0
[term_taxonomy_id] => 3
[taxonomy] => kalba
[description] =>
[parent] => 0
[count] => 7
[object_id] => 135
)
)
want display: [name] => Lietuviu , try $var[3][name], but this not work

That is because that Array is actually an object. Put $var into this function:
function object_to_array($data)
{
if(is_array($data) || is_object($data))
{
$result = array();
foreach($data as $key => $value)
{
$result[$key] = object_to_array($value);
}
return $result;
}
return $data;
}
Like so:
$realArray = object_to_array($var);

The value under the index 3 is a stdClass object, you will have to use the arrow operator -> to get its values:
print $var[3]->name;

As your $var[3] element is an object, you have to access its properties like this:
echo $var[3]->name;

You could use object_to_array as defined or access the value in following way:
$var[3]->name

Related

select array value of an object in php

I'm just a beginner and would like to select a value of an array inside an object. I'm quite lost and don't know how to do.
ie : how to get de value of "thailande" inside this object ?
Forminator_Form_Entry_Model Object
(
[entry_id] => 42
[entry_type] => custom-forms
[form_id] => 24342
[is_spam] => 0
[date_created_sql] => 2020-07-02 11:42:21
[date_created] => 2 Juil 2020
[time_created] => 2 Juil 2020 # 11:42
[meta_data] => Array
(
[select-1] => Array
(
[id] => 87
[value] => thailande
)
[radio-1] => Array
(
[id] => 88
[value] => 1
)
[number-1] => Array
(
[id] => 89
[value] => 10
)
[_forminator_user_ip] => Array
(
[id] => 90
[value] => 84.101.156.169
)
)
[table_name:protected] => politis_5_frmt_form_entry
[table_meta_name:protected] => politis_5_frmt_form_entry_meta
)
thx a lot for your help.
It's fairly straightforward - you just go down the hierarchy one step at a time referencing the index you need.
So, assuming $obj in this example is an instance of Forminator_Form_Entry_Model then you would write
$obj->meta_data["select-1"]["value"]
which will point to the data you're looking for.
N.B. The ->index syntax is used to get properties of an object. the ["index"] syntax is used to get properties of an array.
You can try Callback Functions
function array_search_id($val_for_search, $array_data, $search_in_path='root') {
if(is_array($array_data) && count($array_data) > 0) { // if value has child
foreach($array_data as $key => $value) {
$paths_list = $search_in_path;
// Adding current key to search path
array_push($paths_list, $key);
if(is_array($value) && count($value) > 0) { // if value has child
$res = array_search_id($val_for_search, $value, $paths_list);//callback function
if ($res != null)
return $res;
}
else if($value == $val_for_search){
//if you wants path + result
return end($paths_list);
/*
//if you wants path
return join(" --> ", $paths_list);
*/
} //if value find in array return val
}
}
return null;
}
array_search_id('thailande', $your_array);

How do I skip over first bracket in array with php?

I am needing to echo out the [number], but as you can see each array has a different parent [], how do I by pass the first one and get go to the [number]?
I basically need to skip over first [], and go to the second on that is [number]
Array
(
[e2a4789d22ff47779722b8d8643894cd] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
)
Array
(
[1603ebeff250437480f5ce046cac36aa] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 3
[order] => 0
[preferred] => 1
)
)
Array
(
[215590630122] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[order] => 0
[preferred] =>
)
)
Your solution for this is using the foreach-loop. Which gives you then the value of the element as variable you tell PHP to assign to.
foreach($array as $element) {
}
You have to use reset function to get the first element of array.
e.g.
$firstElement = reset($arr);
echo $firstElement['number'];
You can just loop over the elements in the array(s) using foreach.
foreach($data as $ele){
foreach($ele as $id=>$val){
echo $val['number'];
}
}
Just an example
$array = $yourarray;
foreach($array as $k=>$v) {
echo $v['number'] . '<br>';
}
hope this helps...
The first bracket is just a unique key index foreach subsequent set of data. for example you can get the first set by accessing through the key like this
$data['e2a4789d22ff47779722b8d8643894cd']
// will return
Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
loop through the array to access the data you want,
// declare your array if you want to save data in array
$numbers = [];
foreach($data $key =>$value){
// echo just the number
echo $value['number'];
// echo the key and number
echo $key.' '.$value;
// or you can build an array
$numbers[$key] = $value['number'];
}
print_r($numbers);
Hope you find this useful, for more info about arrays take a look at this http://php.net/manual/en/language.types.array.php
foreach ($array as $id => $element)
{
// will echo 999-999-9999
echo $element['number'];
}
$array is the whole data structure. We go through as index, that is the $id, which is for example e2a4789d22ff47779722b8d8643894cd and the $element is the element in the $array[$id] so in the $array[e2a4789d22ff47779722b8d8643894cd]
So the $element is the small array in the large array, and it contains data like:
Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
So if you need the number attribute, you type $element['number'] and you get it.
If your variable was in an array called $elements then it would look like:
$elements['e2a4789d22ff47779722b8d8643894cd']['number']

PHP: Compare 2 different array/object. Check if a field value exist in the other

I have an object/array like this:
[LineItems] => Array
(
[0] => stdClass Object
(
[ProductNumber] => PAC-051-9716
[Description] => KIT CLOSURE 6" BUTT THRD BLK
[Cost] => 24.84
[ExtCost] => 24.84
[OrdNum] => X4146223
)
)
And the other object/array looks like this:
[0] => VendorBillItem Object
(
[vendorName] => PAC-051-9716
[quantity] => 1
[rate] => 24.84
[amount] => 24.84
)
How can I check if [ProductNumber] field value from the first array exist in the 2nd array by checking it against [vendorName] field value?
Thanks in advance. Cheers!
I recommend you build an index for 2nd array.
foreach ($vendorBills as $key => $vendorBill) {
empty($index[$vendorBill->vendorName]) && $index[$vendorBill->vendorName] = array();
$index[$vendorBill->vendorName][] = $key;
}
After that just check
!empty($index[$lineItem->ProductNumber])
Suppose two arrays are named as $lineitemsArray and $venderBillArray
foreach($lineitemsArray as $lineItem)
{
foreach($venderBillArray as $vendorItem)
{
if($lineItem->ProductNumber==$vendorItem->vendorName)
{
echo "equal";
}
else{
echo "not equal";
}
}
}

values not push on recursive array

Let me explain my problem. I try to generate an array of categories.
Here is my function.
private function recursiveCategoriesTree($id_parent, $level, $categories)
{
$tree = array();
foreach($categories as $categorie)
{
if($id_parent == $categorie['id_parent'])
{
$tree[$level][] = $categorie;
$this->recursiveCategoriesTree($categorie['id_category'], ($level+1), $categories);
}
}
return $tree;
}
When I trace the loop with echo, everything seems to work, all the parent categories and girls are covered, but are not pushed into the array.
Here is the print_r of my categories
array(
[0] => Array
(
[id_category] => 4
[name] => Pièces détachées
[id_parent] => 1
)
[1] => Array
(
[id_category] => 5
[name] => Excavateur
[id_parent] => 4
)
[2] => Array
(
[id_category] => 6
[name] => série 100
[id_parent] => 5
)
[3] => Array
(
[id_category] => 7
[name] => above
[id_parent] => 6
)
[4] => Array
(
[id_category] => 8
[name] => système hydraulique
[id_parent] => 7
)
[5] => Array
(
[id_category] => 9
[name] => série 200
[id_parent] => 5
)
[6] => Array
(
[id_category] => 10
[name] => thru
[id_parent] => 6
)
[7] => Array
(
[id_category] => 11
[name] => Compaction
[id_parent] => 4
)
)
Here is the result of print_r generated
Array(
[0] => Array
(
[0] => Array
(
[id_category] => 5
[name] => Excavateur
[id_parent] => 4
)
[1] => Array
(
[id_category] => 11
[name] => Compaction
[id_parent] => 4
)
)
)
I call my function like that
$tree = $this->recursiveCategoriesTree(4, 0, $categories)
What is the problem ? thank you =)
Either get the return value from your recursive call and push that onto the array, or make a private property of the class called tree and push values onto that instead. You are not passing the variable $tree across recursive function calls.
E.g. if you do this it will work: (EDIT: Fixed... [again])
private $catTree = array();
private $catStartLevel = FALSE;
private function recursiveCategoriesTree($id_parent, $level, $categories) {
if ($this->catStartLevel !== FALSE) $this->catStartLevel = $level;
foreach($categories as $categorie) {
if($id_parent == $categorie['id_parent']) {
$this->catTree[$level][] = $categorie;
$this->recursiveCategoriesTree($categorie['id_category'], ($level+1), $categories);
}
}
if ($this->catStartLevel === $level) {
$tree = $this->catTree;
$this->catTree = array();
$this->catStartLevel = FALSE;
}
return $tree;
}
...however this is not great, because you now have a 'pointless' private property in your class. You would be better to change you array structure, and catch the return values from $this->recursiveCategoriesTree()...
EDIT
Thinking about it, if you really want the array in that structure, you would probably be better to pass the variable to be populated with the array by reference:
private function recursiveCategoriesTree($id_parent, $level, $categories, &$tree) {
foreach($categories as $categorie) {
if($id_parent == $categorie['id_parent']) {
$tree[$level][] = $categorie;
$this->recursiveCategoriesTree($categorie['id_category'], ($level+1), $categories, $tree);
}
}
}
...and then you would call it like this...
$myTree = array();
$obj->recursiveCategoriesTree($id_parent, $level, $categories, $myTree);
print_r($myTree);
recursiveCategoriesTree() returns the $tree, but you're not doing anything with that return value when you're calling the method recursively. You're only storing the $tree returned from the initial call to the method.
Perhaps you want something like this?
$categorie['children'] = $this->recursiveCategoriesTree($categorie['id_category'], ($level+1), $categories);
You should first fetch all the childs of a category, and add them to its array, before appending the category to the tree. Kind of like this:
foreach($categories as $categorie)
{
$categorie['childs'] = $this->recursiveCategoriesTree($categorie['id_category'], ($level+1), $categories);
$tree[$level][] = $categorie;
}

How can I create multidimensional arrays from a string in PHP?

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);
}

Categories