Reading PHP array using key value - php

I have an array that I'm creating inside my PHP script, the var_dump function gives me this value :var_dump($arrayOfValues);
array(3) {
[0]=> array(2) {
[0]=> string(12) "BusinessName"
[1]=> string(13) "ITCompany"
}
[1]=> array(2) {
[0]=> string(7) "Address"
[1]=> string(58) "29 xxxxxx,Canada"
}
[2]=> array(2) {
[0]=> string(20) "PrimaryBusinessPhone"
[1]=> string(14) "(444) 111-1111"
}
[3]=> array(2) {
[0]=> string(13) "BusinessEmail"
[1]=> string(24) "xx#example.com"
}
}
I would like to access to the value of the "BusinessName" using key and not index so if I put : echo $arrayOfValue[0][1]; it gives me the BusinessName that is ITCompany but if I put
: echo $arrayOfValue['BusinessName'][1]; it gives nothing so how can I fix that please?
The array is initialized $arrayOfValue = array(); and then populated dynamically inside a for loop like that
$arrayOfValue[] = array($Label, $Value);

your array has this kind of data
$arrayOfPostsValue[] = array("BusinessName","ITCompany");
$arrayOfPostsValue[] = array("Address","29 xxxxxx,Canada");
$arrayOfPostsValue[] = array("PrimaryBusinessPhone","(444) 111-1111");
$arrayOfPostsValue[] = array("BusinessEmail","xx#example.com");
there is no array key in data So, you have to recreate your desire array
$newArrayOfPostsValue = array();
foreach ( $arrayOfPostsValue as $value ){
$newArrayOfPostsValue[$value[0]] = $value[1];
}
print_r($newArrayOfPostsValue);
and here is output
Array
(
[BusinessName] => ITCompany
[Address] => 29 xxxxxx,Canada
[PrimaryBusinessPhone] => (444) 111-1111
[BusinessEmail] => xx#example.com
)

As mentioned in the comment, change the structure of the array, it will be much easier to handle
$my_array = array(
array('Business Name' => 'It Company'),
array('Address' => 'My address')
);
Looking at the content of your array, I will restructure it as
$my_improved_array = array(
'BusinessName' => 'It Company',
'Address' => 'My Address',
);
This is how you can access,
echo $my_array[0]['BusinessName'] //prints 'It Company'
echo $my_array[1]['Address'] //prints 'My Address'
echo $my_improved_array['BusinessName'] // prints 'It Company'

Try like this and save array as key value pairs and then access the key:
foreach($arrayOfValues as $a)
$arr[$a[0]] = $a[1];
echo $arr['BusinessName'];

While creating that array build it with index as BusinessName
array (
0 => array(
'BusinessName'=> "ITCompany"
)
1 => array(1) (
'Address'=> "29 xxxxxx,Canada"
)
)
etc..

PHP Array example
$array = array();
$array['BusinessName'] = 'ITCompany';
$array['Address'] = '29 xxxxxx,Canada';
And so on... Now you can echo values with
echo $array['BusinessName'];
Also this works
$array = array('BusinessName' => 'ITCompany', 'Address' => '29 xxxxxx,Canada');

First of all, how are you building this array ? Maybe you can directly make a workable array.
Anyway, you can do something like this :
$oldArray = Array(
Array("BusinessName", "ITCompany"),
Array("Address", "29 xxxxxx,Canada"),
Array("PrimaryBusinessPhone", "(444) 111-1111"),
Array("BusinessEmail", "xx#example.com")
);
$newArray = Array();
foreach($oldArray as value) {
$newValue[$value[0]] = $value[1];
}
/* Now, it's equal to
$newArray = Array(
"BusinessName" => "ITCompany",
"Address" => "29 xxxxxx,Canada",
"PrimaryBusinessPhone" => "(444) 111-1111",
"BusinessEmail" => "xx#example.com"
);
*/

Related

Not able to access data inside a PHP array of object

I´m trying to access data inside a object create after a response(from a dafiti server) with no succsess.
Bellow my code:
***$response = Endpoints::order()->getOrder($orderId)->call($client);
$o = $response->getBody();
echo "<pre>";
var_dump($o);
echo "</pre>";
foreach($o as $value => $obj){
$orderId = $obj->Order->OrderID;// tried this way(not working)
$CustomerFirstName = $obj['Order']['CustomerFirstName'];// tried this way(not working)
}******
Bellow the var_dump:
array(1) {
["Orders"]=>
array(1) {
["Order"]=>
array(23) {
["OrderId"]=>
string(7) "8266761"
["CustomerFirstName"]=>
string(6) "sheila"
["CustomerLastName"]=>
string(14) "rocha domingos"
["OrderNumber"]=>
string(10) "4510948375"
["PaymentMethod"]=>
string(22) "braspag_cc_master_card"
["Currency"]=>
string(3) "BRL"
... to be continue.
How can I access the values inside this array?
Your array contains an array of orders inside of the 'Orders' field of the $o array. So you need to iterate over $o['Orders']. Then you'll be able to access your order details.
<?php
$o = [
'Orders' => [
'Order' => [
'OrderId' => '8266761',
'CustomerFirstName' => 'sheila',
'CustomerLastName' => 'rocha domingos',
'OrderNumber' => '4510948375',
'PaymentMethod' => 'braspag_cc_master_card',
'Currency' => 'BRL'
]
]
];
foreach ($o['Orders'] as $order) {
$orderId = $order['OrderId'];
$CustomerFirstName = $order['CustomerFirstName'];
var_dump($orderId); // 8266761
var_dump($CustomerFirstName); // sheila
}

php get associative array in place normal array as result of function

i create function who return normal array :
function get_list_array () {
$list_object = get_list_objects();
foreach ( $list_object as $every_object) {
$list_array[] = array (
"wprm_$every_object->name" => array (
'name' => _x("$every_object->label", , 'test'),
'singular_name' => _x("$every_object->name", , 'test'),));
}
return $list_array ;
}
var_dump ($list_array);
array(2) {
[0]=> array(1) { ["object_1"]=> array(2) {
["name"]=> string(10)
"name_object1" ["singular_name"]=> string(15) "singular_name_object1" } }
[1]=> array(1) { ["object_2"]=> array(2) {
["name"]=> string(4)
"name_object2" ["singular_name"]=> string(10) "singular_name2" } } }
And i want the get in place just the associative array like this:
array ("object_1" => array (["name"]=> string(10) "name_object1"
["singular_name"]=> string(15) "singular_name_object1" } ,
"object_2" => array(2) {
["name"]=> string(4)
"name_object2" ["singular_name"]=> string(10) "singular_name2" } } }
any idea how i can modify my function in order the get the second output.
You're wrapping the array you actually want into another array by doing this:
$list_array[] = array(
"wprm_$every_object->name" => array(
Instead, you should simply assign the new array to $list_array directly:
$list_array["wprm_$every_object->name"] = array(
Also, please think about how you indent your code, because wow. Your function could look like this:
function get_list_array () {
$list_object = get_list_objects();
foreach ($list_object as $every_object) {
$list_array["wprm_$every_object->name"] = array(
'name' => _x("$every_object->label", , 'test'),
'singular_name' => _x("$every_object->name", , 'test'),
);
}
return $list_array;
}

How can I flatten a Multidimensional array into a string?

Ive researched this but im coming up blank, Im generating an array of tests from a database like so:
$descriptions = array();
foreach ($tests as $value) {
array_push($descriptions, ['name' => $value['name']]);
}
I'm getting the desired out put but i'm getting a Multidimensional array of an array with '[64]' arrays inside '$descriptions', I need to convert this array so I get the following output:
'name' => $value1, 'name' => $value2, etc etc for all results,
I've tried implode, array_merge etc but the closest I've got is a flat array with only my last test: [name] => Zika can anyone point me in the right direction? cheers
You can't have duplicate array keys. But you can pass an array in like so:
<?php
$descriptions = array();
$tests = array(
'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',
);
foreach ($tests as $value) {
$descriptions[] = array('name' => $value);
}
var_dump($descriptions);
Which gives you :
array(6) { [0]=> array(1) { ["name"]=> string(4) "Zika" } [1]=> array(1) { ["name"]=> string(4) "SARS" } [2]=> array(1) { ["name"]=> string(4) "AIDS" } [3]=> array(1) { ["name"]=> string(15) "Mad Cow Disease" } [4]=> array(1) { ["name"]=> string(8) "Bird Flu" } [5]=> array(1) { ["name"]=> string(16) "Zombie Infection" } }
So you could foreach ($descriptions as $desc) and echo $desc['name']';
Have a look here: https://3v4l.org/pWSC6
If you just want a string, try this:
<?php
$descriptions = '';
$tests = array(
'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',
);
foreach ($tests as $value) {
$descriptions .= 'name => '.$value.', ';
}
$descriptions = substr($descriptions, 0, -2); // lose the last comma
echo $descriptions;
Which will output:
name => Zika, name => SARS, name => AIDS, name => Mad Cow Disease, name => Bird Flu, name => Zombie Infection
See it here https://3v4l.org/OFGF4

How to change name of keys of a multidimensional array

I have two arrays one of them contain a new key name
$assoc = ['name', 'lastname', 'pesel'];
and second look this
$inputs = ['John', 'Don', '987987', 'Mike', 'Evans', '89779' ];
Array $assoc is the new key name, and I would like to change [0],[1] to ['name'] etc
array(2) {
['person'] =>
array(3) {
['name'] => string(4) "John"
['lastname'] => string(3) "Don"
['pesel'] => string(6) "987987"
}
['person'] =>
array(3) {
['name'] => string(4) "Mike"
['lastname'] => string(5) "Evans"
['pesel'] => string(5) "89779"
}
}
Thanks for your help
It's pretty simple:
$new_array = array();
foreach(array_chunk($inputs, 3) as $person) {
$new_array[] = array_combine($assoc, $person);
}
<?php
$assoc=Array("name", "lastname", "pesel");
$inputs=Array('John', 'Don', '987987', 'Mike', 'Evans', '89779' );
$resultant_array=Array();
for($i=0; $i<count($inputs); $i+=count($assoc)){
//echo $i."\n\n";
for($j=0; $j<count($assoc); $j++){
$b2g[$assoc[$j]]=$inputs[$i+$j];
}
$resultant_array[]=$b2g;
}
print_r($resultant_array);
It is a more lengthy and general purpose use.. I actually have used much recurssions..

Rebase array keys after unsetting elements [duplicate]

This question already has answers here:
How to re-index the values of an array in PHP? [duplicate]
(3 answers)
Closed 2 years ago.
I have an array:
$array = array(1,2,3,4,5);
If I were to dump the contents of the array they would look like this:
array(5) {
[0] => int(1)
[1] => int(2)
[2] => int(3)
[3] => int(4)
[4] => int(5)
}
When I loop through and unset certain keys, the index gets all jacked up.
foreach($array as $i => $info)
{
if($info == 1 || $info == 2)
{
unset($array[$i]);
}
}
Subsequently, if I did another dump now it would look like:
array(3) {
[2] => int(3)
[3] => int(4)
[4] => int(5)
}
Is there a proper way to reset the array so it's elements are Zero based again ??
array(3) {
[0] => int(3)
[1] => int(4)
[2] => int(5)
}
Try this:
$array = array_values($array);
Using array_values()
Got another interesting method:
$array = array('a', 'b', 'c', 'd');
unset($array[2]);
$array = array_merge($array);
Now the $array keys are reset.
Use array_splice rather than unset:
$array = array(1,2,3,4,5);
foreach($array as $i => $info)
{
if($info == 1 || $info == 2)
{
array_splice($array, $i, 1);
}
}
print_r($array);
Working sample here.
Just an additive.
I know this is old, but I wanted to add a solution I don't see that I came up with myself. Found this question while on hunt of a different solution and just figured, "Well, while I'm here."
First of all, Neal's answer is good and great to use after you run your loop, however, I'd prefer do all work at once. Of course, in my specific case I had to do more work than this simple example here, but the method still applies. I saw where a couple others suggested foreach loops, however, this still leaves you with after work due to the nature of the beast. Normally I suggest simpler things like foreach, however, in this case, it's best to remember good old fashioned for loop logic. Simply use i! To maintain appropriate index, just subtract from i after each removal of an Array item.
Here's my simple, working example:
$array = array(1,2,3,4,5);
for ($i = 0; $i < count($array); $i++) {
if($array[$i] == 1 || $array[$i] == 2) {
array_splice($array, $i, 1);
$i--;
}
}
Will output:
array(3) {
[0]=> int(3)
[1]=> int(4)
[2]=> int(5)
}
This can have many simple implementations. For example, my exact case required holding of latest item in array based on multidimensional values. I'll show you what I mean:
$files = array(
array(
'name' => 'example.zip',
'size' => '100000000',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example.zip',
'size' => '10726556',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example.zip',
'size' => '110726556',
'type' => 'application/x-zip-compressed',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example2.zip',
'size' => '12356556',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example2.zip',
'deleteUrl' => 'server/php/?file=example2.zip',
'deleteType' => 'DELETE'
)
);
for ($i = 0; $i < count($files); $i++) {
if ($i > 0) {
if (is_array($files[$i-1])) {
if (!key_exists('name', array_diff($files[$i], $files[$i-1]))) {
if (!key_exists('url', $files[$i]) && key_exists('url', $files[$i-1])) $files[$i]['url'] = $files[$i-1]['url'];
$i--;
array_splice($files, $i, 1);
}
}
}
}
Will output:
array(1) {
[0]=> array(6) {
["name"]=> string(11) "example.zip"
["size"]=> string(9) "110726556"
["type"]=> string(28) "application/x-zip-compressed"
["deleteUrl"]=> string(28) "server/php/?file=example.zip"
["deleteType"]=> string(6) "DELETE"
["url"]=> string(44) "28188b90db990f5c5f75eb960a643b96/example.zip"
}
[1]=> array(6) {
["name"]=> string(11) "example2.zip"
["size"]=> string(9) "12356556"
["type"]=> string(28) "application/x-zip-compressed"
["deleteUrl"]=> string(28) "server/php/?file=example2.zip"
["deleteType"]=> string(6) "DELETE"
["url"]=> string(45) "28188b90db990f5c5f75eb960a643b96/example2.zip"
}
}
As you see, I manipulate $i before the splice as I'm seeking to remove the previous, rather than the present item.
I use $arr = array_merge($arr); to rebase an array. Simple and straightforward.
100% working for me ! After unset elements in array you can use this for re-indexing the array
$result=array_combine(range(1, count($your_array)), array_values($your_array));
Late answer but, after PHP 5.3 could be so;
$array = array(1, 2, 3, 4, 5);
$array = array_values(array_filter($array, function($v) {
return !($v == 1 || $v == 2);
}));
print_r($array);
Or you can make your own function that passes the array by reference.
function array_unset($unsets, &$array) {
foreach ($array as $key => $value) {
foreach ($unsets as $unset) {
if ($value == $unset) {
unset($array[$key]);
break;
}
}
}
$array = array_values($array);
}
So then all you have to do is...
$unsets = array(1,2);
array_unset($unsets, $array);
... and now your $array is without the values you placed in $unsets and the keys are reset
In my situation, I needed to retain unique keys with the array values, so I just used a second array:
$arr1 = array("alpha"=>"bravo","charlie"=>"delta","echo"=>"foxtrot");
unset($arr1);
$arr2 = array();
foreach($arr1 as $key=>$value) $arr2[$key] = $value;
$arr1 = $arr2
unset($arr2);

Categories